You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何查找列表内出现最频繁的子列表及对应计数

解决嵌套列表中统计最频繁子列表的问题

你说得对,collections.Counter确实没法直接接受列表作为元素——因为列表是可变、不可哈希的类型,而Counter的键必须是可哈希的。不过解决这个问题的思路很简单:把每个子列表转换成可哈希的类型就行,最常用的就是元组(tuple)。

下面给你两种实用的解决方案:

方法一:用Counter+元组转换(最简洁)

这是最直接的方式,先把所有子列表转成元组,再用Counter统计,最后把结果转回去即可:

from collections import Counter

my_list = [[10, 2, 14], [1, 4, 6], [2, 3, 4], [10, 2, 14]]

# 把每个子列表转为元组(元组不可变,支持哈希)
tuple_sublists = [tuple(sublist) for sublist in my_list]

# 统计元组的出现次数
count_result = Counter(tuple_sublists)

# 获取出现次数最多的元素(most_common(1)返回一个包含元组的列表)
most_frequent_item = count_result.most_common(1)[0]

# 把元组转回列表,得到最终结果
final_result = (list(most_frequent_item[0]), most_frequent_item[1])
print(final_result)  # 输出: ([10, 2, 14], 2)

方法二:手动用字典统计(无需依赖Counter)

如果不想导入Counter模块,也可以自己用字典实现统计逻辑,原理和上面一样:

my_list = [[10, 2, 14], [1, 4, 6], [2, 3, 4], [10, 2, 14]]

count_dict = {}
for sublist in my_list:
    # 用元组作为字典的键
    key = tuple(sublist)
    # 累加计数,不存在则默认0
    count_dict[key] = count_dict.get(key, 0) + 1

# 找出最大计数
max_count = max(count_dict.values())
# 找到对应最大计数的子列表(转回列表)
most_frequent_sublist = list(next(k for k, v in count_dict.items() if v == max_count))

final_result = (most_frequent_sublist, max_count)
print(final_result)  # 输出: ([10, 2, 14], 2)

核心逻辑总结:只要把不可哈希的列表转换成可哈希的元组,就可以用常规的哈希表工具(Counter或字典)来统计出现次数了。

内容的提问来源于stack exchange,提问作者Rake146

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:37:53