为了账号安全,请及时绑定邮箱和手机立即绑定

计算多个字典键的 Pythonic 方法

计算多个字典键的 Pythonic 方法

慕妹3242003 2022-06-14 10:07:05
假设有 3 个字典first, second,third具有以下值first = {'a': 0.2, 'b': 0.001}second = {'a': 0.99, 'c': 0.78}third = {'c': 1, 'd': 0.1}total = {'_first': first, '_second': second, '_third':third}有没有一种方法可以快速获得一个数据结构,它可以使用而不是多个字典来保存每个键(a, b, c, )的计数信息。例如,答案应该返回类似since , , key在这些字典中出现两次而只出现一次的内容。dtotal{'a':2, 'b':2, 'c':2, 'd':1}abcd
查看完整描述

3 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

from collections import Counter

from itertools import chain

first = {'a': 0.2, 'b': 0.001}

second = {'a': 0.99, 'c': 0.78}

third = {'c': 1, 'd': 0.1}

print(Counter(chain(first, second, third)))

以存储在字典中的可变数量的字典来解释已编辑的问题total


total = {'_first': first, '_second': second, '_third':third}

print(Counter(chain.from_iterable(total.values())))


查看完整回答
反对 回复 2022-06-14
?
慕容3067478

TA贡献1773条经验 获得超3个赞

没有任何进口:


def dict_keys_count(*dicts):

    keys = []

    for _dict in dicts:

        keys += _dict.keys()


    keys_counts = {}

    for key in set(keys):

        keys_counts[key] = keys.count(key)


    return keys_counts

print(dict_keys_count(first,second,third))

# {'b': 1, 'c': 2, 'd': 1, 'a': 2}

速度比较:我与接受的答案


from time import time


t0 = time()

for _ in range(int(1e7)):

    dict_keys_count(first,second,third)

print("No-import solution {}:".format(time() - t0))

# 17.77


t0 = time()

for _ in range(int(1e7)):

    Counter(chain(first, second, third))

print("Accepted solution {}:".format(time() - t0))

# 24.01


查看完整回答
反对 回复 2022-06-14
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

您可以使用collections.Counter:


import collections

first = {'a': 0.2, 'b': 0.001}

second = {'a': 0.99, 'c': 0.78}

third = {'c': 1, 'd': 0.1}

r = dict(collections.Counter([*first, *second, *third]))

输出:


{'a': 2, 'c': 2, 'b': 1, 'd': 1}


查看完整回答
反对 回复 2022-06-14
  • 3 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号