Python:如何将列表元素按唯一/重复分类存入字典对应列表?
问题分析
你的代码核心问题是:每次循环都直接给字典的键赋值单个元素,而非往列表中追加内容。比如dictionary["unique"] = items会覆盖之前的取值,最终只能保留最后一个符合条件的元素。要实现将元素存入对应列表,必须先把字典的两个键初始化为空列表,再用append()方法添加元素。
修正后的代码(保留所有重复元素实例)
numbers = [20, 20, 20, 2, 10, 10, 1] # 先初始化两个键对应的空列表,为后续追加元素做准备 dictionary = {"unique": [], "duplicate": []} for item in numbers: count = numbers.count(item) if count == 1: dictionary["unique"].append(item) else: dictionary["duplicate"].append(item) print(dictionary)
运行结果:
{'unique': [2, 1], 'duplicate': [20, 20, 20, 10, 10]}
可选:去重后的重复项列表
如果你的目标是让duplicate仅保留重复元素的唯一实例(比如类似你示例中的[20, 10]),可以通过集合记录已添加的重复元素来实现:
numbers = [20, 20, 20, 2, 10, 10, 1] dictionary = {"unique": [], "duplicate": []} seen_duplicates = set() # 用集合避免重复添加同一元素 for item in numbers: count = numbers.count(item) if count == 1: dictionary["unique"].append(item) else: if item not in seen_duplicates: dictionary["duplicate"].append(item) seen_duplicates.add(item) print(dictionary)
运行结果:
{'unique': [2, 1], 'duplicate': [20, 10]}
内容的提问来源于stack exchange,提问作者Aprend
相关产品推荐
相关产品推荐

