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

如何高效统计Python列表中两数组合的出现次数?

解决Python中列表子元素的统计问题

你遇到的核心问题是:collections.Counter只能统计可哈希类型的元素,而列表(list)属于不可哈希类型,直接传入会触发TypeError。下面是两种高效的解决方法:

方法一:转换为元组后使用Counter(推荐)

将每个子列表转换为可哈希的元组,再用Counter完成统计,最后按需求格式化输出:

from collections import Counter

MyList = [[1,2], [2,3], [1,3], [1,2],[1,2],[2,2],[3,3],[2,2]]
# 将子列表转为元组(元组是可哈希类型,可作为Counter的统计对象)
tuple_list = [tuple(sub) for sub in MyList]
count_result = Counter(tuple_list)

# 按目标格式输出统计结果
for item_tuple, count in count_result.items():
    print(f"{list(item_tuple)} = {count}")

执行后会输出:

[1, 2] = 3
[2, 3] = 1
[1, 3] = 1
[2, 2] = 2
[3, 3] = 1

方法二:手动使用字典统计

如果不想依赖Counter,也可以用字典手动实现统计逻辑:

MyList = [[1,2], [2,3], [1,3], [1,2],[1,2],[2,2],[3,3],[2,2]]
count_dict = {}

for sub_list in MyList:
    # 用元组作为字典的键(列表无法直接作为字典键)
    key = tuple(sub_list)
    count_dict[key] = count_dict.get(key, 0) + 1

# 格式化输出结果
for key, count in count_dict.items():
    print(f"{list(key)} = {count}")

效率说明

collections.Counter是Python标准库中专门为频次统计优化的工具,代码更简洁且执行效率更高,优先推荐使用第一种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:52:28