Python遍历列表存储前序值 实现相邻异值追加的代码问题排查
问题说明
现有一段Python代码,目标是遍历主列表,按「元素和前一个遍历值是否匹配」的规则生成结果列表append_list,具体规则:
- 主列表第一个元素没有前置对比项,直接加入结果列表
- 后续元素如果和紧邻的上一个遍历值相同则跳过,不同则追加到结果列表
- 最终结果列表保留所有和前一个遍历值不一致的元素
原代码运行后,append_list仅包含初始化的空字符串和第一个元素"Apple",不符合预期。原代码如下:
''' -- Append the first element in the append list as it has no previous element -- After that check if the second element is same as first element -- if same: Do nothing , if different : Append to the append list -- The append list will be populated with all the values which don't match their previous values ''' main_list = ['Apple', 'Apple', 'Apple', 'Apple', 'bat', 'bat', 'bat1', 'bat', 'cat', 'cat', 'cat', 'cat1', 'cat', 'cat', 'Apple', 'Apple', 'Apple', 'Apple'] append_list = [''] previous_item = [] previous_item_2 = [''] for item in main_list: previous_item.append(item) if previous_item[0] != previous_item_2[0]: append_list.append(item) previous_item_2 = [] previous_item_2.append(item) else : pass print(append_list)
错误原因排查
原代码核心逻辑存在明显错误:
- 用于存储遍历记录的
previous_item只做追加操作、从不清理元素,每次对比都固定取索引0的元素,也就是第一次循环存入的第一个"Apple",后续遍历到的所有元素都存在列表靠后的位置,永远不会参与对比。第一次循环走完后previous_item_2存储的值也是"Apple",之后所有循环的判断都是两个固定的"Apple"做对比,永远相等,自然不会再追加新元素到结果列表。 - 初始化
append_list时提前塞入空字符串、用两个列表存储单个前置值的写法完全冗余,额外提升了逻辑出错的概率。 - 打印语句放在循环内部,会逐次输出每次循环的中间结果,没有必要。
修正后的实现
不需要用列表存储前置值,直接用单个变量记录上一个遍历到的元素即可,逻辑更简单也不容易出错,同时兼容主列表为空的边界情况:
main_list = ['Apple', 'Apple', 'Apple', 'Apple', 'bat', 'bat', 'bat1', 'bat', 'cat', 'cat', 'cat', 'cat1', 'cat', 'cat', 'Apple', 'Apple', 'Apple', 'Apple'] append_list = [] if main_list: # 直接加入第一个元素 append_list.append(main_list[0]) prev_val = main_list[0] # 从第二个元素开始遍历对比 for current_val in main_list[1:]: if current_val != prev_val: append_list.append(current_val) prev_val = current_val print(append_list)
运行后得到的正确输出为:
['Apple', 'bat', 'bat1', 'bat', 'cat', 'cat1', 'cat', 'Apple']
完全符合规则要求:所有和紧邻前一个遍历值不同的元素都被保留,连续重复的相邻元素仅保留第一个。
内容的提问来源于stack exchange,提问作者Abhishake Yadav
相关产品推荐
相关产品推荐

