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

如何统计Python字典列表中多键组合值的出现次数?

统计多键组合值的出现次数

没问题,要统计多个键(比如first_name和last_name的组合)的出现次数,核心是把这两个键的取值打包成一个可哈希的元组,再用Counter来统计。咱们来修改你的函数:

修改后的完整函数

from collections import Counter

def count_names(dict_nomi):
    # 生成(first_name, last_name)元组的迭代器,同时确保两个键都存在
    name_pairs = Counter(
        (v['first_name'], v['last_name']) 
        for v in dict_nomi 
        if v.get('first_name') and v.get('last_name')
    )
    # 遍历统计结果,注意变量名不要和Counter对象重名
    for name_pair, count in name_pairs.most_common():
        # 格式化输出全名和次数
        print(f"{name_pair[0]} {name_pair[1]}: {count}")

运行效果

用你给出的dict_nomi列表测试:

dict_nomi = [ 
    {"first_name": "Luca", "last_name": "Rossi"}, 
    {"first_name": "Stefano", "last_name": "De Rosso"}, 
    {"first_name": "Luca", "last_name": "Bianchi"}, 
    {"first_name": "Luca", "last_name": "Rossi"}, 
]

count_names(dict_nomi)

输出结果:

Luca Rossi: 2
Stefano De Rosso: 1
Luca Bianchi: 1

更灵活的扩展版本(支持任意多键)

如果以后需要统计其他键组合,比如加上middle_name,可以把函数改成支持传入指定键列表:

from collections import Counter

def count_key_combinations(dict_list, keys=('first_name', 'last_name')):
    key_combinations = Counter(
        tuple(v[key] for key in keys)
        for v in dict_list
        # 确保所有指定的键都存在于字典中
        if all(key in v for key in keys)
    )
    for combo, count in key_combinations.most_common():
        # 把元组转换成空格分隔的字符串
        combo_str = ' '.join(combo)
        print(f"{combo_str}: {count}")

调用的时候可以指定键:

count_key_combinations(dict_nomi, keys=('first_name', 'last_name'))

这样不管是2个键还是更多,都能轻松适配啦~

内容的提问来源于stack exchange,提问作者Stefano De Rosso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:16:58