Python列表元素合并:如何将'machine'与'gun'合并为'machinegun'
问题:合并列表中相邻的指定元素
我有一个名为cleaned_text的列表:
cleaned_text = ['#bullhornlady', 'in', 'the', 'same', 'pic', 'with', 'the', 'same', 'horn', 'guess', 'this', 'pic', 'is', 'how', '#eyegouger', 'got', 'his', 'designation', 'i', 'see', 'a', 'machine', 'gun', 'behind', 'him']
需要把其中的'machine'和'gun'合并为'machinegun',得到如下结果:
cleaned_text = ['#bullhornlady', 'in', 'the', 'same', 'pic', 'with', 'the', 'same', 'horn', 'guess', 'this', 'pic', 'is', 'how', '#eyegouger', 'got', 'his', 'designation', 'i', 'see', 'a', 'machinegun', 'behind', 'him']
我尝试用以下循环实现,但无法成功合并对应索引的元素:
def white_space_problem(cleaned_text): for next_idx, value in enumerate(cleaned_text[:-1], 1): if value == 'machine' and cleaned_text[next_idx] == 'gun': pass
解决方案
你的循环仅做了条件判断,没有执行实际的合并操作。以下是两种可行的实现方式:
方法1:构建新列表(推荐)
通过遍历原列表,将元素添加到新列表中,遇到需要合并的相邻元素时,合并后再添加,避免修改原列表导致的索引混乱:
def white_space_problem(cleaned_text): result = [] i = 0 while i < len(cleaned_text): # 检查当前元素和下一个元素是否为目标组合 if i < len(cleaned_text) - 1 and cleaned_text[i] == 'machine' and cleaned_text[i+1] == 'gun': result.append('machinegun') i += 2 # 跳过已合并的下一个元素 else: result.append(cleaned_text[i]) i += 1 return result # 调用示例 cleaned_text = ['#bullhornlady', 'in', 'the', 'same', 'pic', 'with', 'the', 'same', 'horn', 'guess', 'this', 'pic', 'is', 'how', '#eyegouger', 'got', 'his', 'designation', 'i', 'see', 'a', 'machine', 'gun', 'behind', 'him'] cleaned_text = white_space_problem(cleaned_text) print(cleaned_text)
方法2:原地修改原列表
如果需要直接修改原列表,找到目标元素后合并并删除相邻元素,同时调整遍历索引:
def white_space_problem(cleaned_text): i = 0 while i < len(cleaned_text) - 1: if cleaned_text[i] == 'machine' and cleaned_text[i+1] == 'gun': # 合并两个元素 cleaned_text[i] = 'machinegun' # 删除被合并的下一个元素 del cleaned_text[i+1] # 不递增索引,因为删除后后续元素已前移 else: i += 1 return cleaned_text
内容的提问来源于stack exchange,提问作者Garrett Austin
相关产品推荐
相关产品推荐

