Python中如何仅显示列表中的重复值(每个重复值仅展示一次)
提取列表中仅出现一次的重复元素
原代码与问题
用户代码:
random_list=['a','b','c','b','d','m','n','n'] duplicates=[] for value in random_list: if random_list.count(value) > 1: if value is not duplicates: duplicates.append(value) print(duplicates)
运行后输出:
[] ['b'] ['b'] ['b', 'b'] ['b', 'b'] ['b', 'b'] ['b', 'b', 'n'] ['b', 'b', 'n', 'n']
需求:仅展示每个重复值一次,得到结果['b','n'],不修改原列表,只提取重复元素。
问题分析
if value is not duplicates逻辑错误:单个元素和列表用is not比较永远为真,导致每次遇到重复元素都会追加到结果里。- 每次调用
random_list.count(value)会遍历整个列表,元素量大时效率偏低。
解决方案
方法1:修正判断条件(适合初学者理解)
直接检查元素是否已在结果列表中,仅当元素重复且未被加入结果时才追加:
random_list=['a','b','c','b','d','m','n','n'] duplicates=[] for value in random_list: if random_list.count(value) > 1: if value not in duplicates: duplicates.append(value) print(duplicates) # 输出: ['b', 'n']
方法2:用集合优化效率(更高效)
通过两个集合分别记录已见过的元素和重复元素,仅遍历一次列表:
random_list=['a','b','c','b','d','m','n','n'] seen = set() duplicates = set() for value in random_list: if value in seen: duplicates.add(value) else: seen.add(value) print(list(duplicates)) # 输出: ['b', 'n']
方法3:简洁的集合推导式写法
利用集合自动去重的特性,一行代码实现:
random_list=['a','b','c','b','d','m','n','n'] duplicates = list({x for x in random_list if random_list.count(x) > 1}) print(duplicates) # 输出: ['b', 'n']
注:Python 3.7+集合会保留插入顺序,旧版本可能顺序不一致。
内容的提问来源于stack exchange,提问作者CatdoesPython
相关产品推荐
相关产品推荐

