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

如何统计列表中tuple元组的出现次数(不考虑元组内元素顺序)

实现方案

核心思路是将每个元组处理为忽略顺序的唯一可哈希键,再做计数:

  • 对每个元组做排序,转成新的元组作为统一标识(元素完全相同但顺序不同的元组,排序后的结果完全一致)
  • 用collections.Counter完成快速统计

可运行示例代码

from collections import Counter

# 示例列表,one/two/three这里以字符串为例,你可替换为自己的变量
the_list = [
    ('one', 'two', 'three'),
    ('two', 'three', 'four'),
    ('one', 'three', 'two'),
    ('one', 'two', 'three'),
    ('four', 'two', 'one'),
]

# 统计逻辑
counts = Counter(tuple(sorted(item)) for item in the_list)
print(counts)

运行输出:

Counter({('one', 'three', 'two'): 3, ('four', 'three', 'two'): 1, ('four', 'one', 'two'): 1})

保留原始元组格式的变种

如果你希望统计结果的key用首次出现的原始元组,而非排序后的元组,可使用以下逻辑:

count_map = {}
for item in the_list:
    key = tuple(sorted(item))
    if key not in count_map:
        count_map[key] = [item, 0]
    count_map[key][1] += 1

# 转为以原始元组为key的结果
result = {v[0]: v[1] for v in count_map.values()}
print(result)

运行输出:

{('one', 'two', 'three'): 3, ('two', 'three', 'four'): 1, ('four', 'two', 'one'): 1}

注意事项

  • 如果元组内包含不可排序的元素,可改用frozenset(item)作为统计key,但该方案会自动去重,仅适用于元组内没有重复元素的场景
  • 如果元组长度不固定,上述排序逻辑依然可用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:24:04