查找列表最高频元素时,如何解决统计结果列表仅存储单条数据的问题
问题原因
- 核心错误是你把
all_data = []写在了for循环内部,每次遍历元素时都会清空之前的列表、重新创建空列表,只有最后一次循环append的数据会被保留,所以最终输出只剩最后一条统计项。 - 额外的拼写隐患:你在生成集合的代码里把列表名写错了,
gather_occurances和原变量名gather_occurrences少了一个字母r,你后续手动给unique_occurrences赋值了集合所以暂时没触发报错,删除手动赋值行就会运行失败。
修正后的代码
gather_occurrences = ['CAT', 'BIRD', 'DOG', 'BIRD', 'DOG', 'CAT', 'BIRD', 'RAT'] # 修正拼写错误,直接从原列表生成唯一值集合,不需要手动赋值 unique_occurrences = set(gather_occurrences) counting = 1 # 将列表初始化移到for循环外部 all_data = [] for x in unique_occurrences: count = gather_occurrences.count(x) each_item = { counting : {x : count }} counting += 1 all_data.append(each_item) print(each_item) print(all_data)
运行输出
{1: {'CAT': 2}} {2: {'BIRD': 3}} {3: {'RAT': 1}} {4: {'DOG': 2}} [{1: {'CAT': 2}}, {2: {'BIRD': 3}}, {3: {'RAT': 1}}, {4: {'DOG': 2}}]
拓展优化(可选)
如果不需要序号做key,只想直接存储所有元素的统计结果为字典,可以用更简洁的写法:
count_dict = {x: gather_occurrences.count(x) for x in set(gather_occurrences)} print(count_dict) # 输出:{'CAT': 2, 'BIRD': 3, 'RAT': 1, 'DOG': 2}
如果要找出现次数最多的元素,直接用max方法即可:
most_item = max(count_dict.items(), key=lambda x: x[1]) print(most_item) # 输出:('BIRD', 3)
内容的提问来源于stack exchange,提问作者Barry Marples
相关产品推荐
相关产品推荐

