【问题标题】:Adding and combining values with dictionary comprehensions?使用字典推导添加和组合值?
【发布时间】:2014-11-13 03:53:48
【问题描述】:

假设我有一个列表:

a_list = [["Bob", 2], ["Bill", 1], ["Bob", 2]]

我想将这些添加到字典中并将值组合到相应的键。所以,在这种情况下,我想要一个看起来像这样的字典:

{"Bob" : 4, "Bill" : 1}

如何使用字典推导来做到这一点?

这就是我所拥有的:

d1 = {group[0]: int(group[1]) for group in a_list}

【问题讨论】:

标签: python dictionary dictionary-comprehension


【解决方案1】:

要使用字典理解做你想做的事,你需要一个外部 extra 字典来跟踪到目前为止每个名称的值:

memory = {}
{name: memory[name] for name, count in a_list if not memory.__setitem__(name, count + memory.setdefault(name, 0))}

但这会产生 两个 带有总和的字典:

>>> a_list = [["Bob", 2], ["Bill", 1], ["Bob", 2]]
>>> memory = {}
>>> {name: memory[name] for name, count in a_list if not memory.__setitem__(name, count + memory.setdefault(name, 0))}
{'Bob': 4, 'Bill': 1}
>>> memory
{'Bob': 4, 'Bill': 1}

这是因为没有 memory 字典,您无法访问每个名称的运行总和。

此时你不妨只使用字典和常规循环:

result = {}
for name, count in a_list:
    result[name] = result.get(name, 0) + count

collections.defaultdict() object:

from collections import defaultdict

result = defaultdict(int)
for name, count in a_list:
    result[name] += count

甚至是collections.Counter() object,为您提供额外的多组功能供以后使用:

from collections import Counter

result = Counter()
for name, count in a_list:
    result[name] += count

另一个效率较低的选择是先对a_list 进行排序,然后使用itertools.groupby)()

from itertools import groupby
from operator import itemgetter

key = itemgetter(0)  # sort by name
{name: sum(v[1] for v in group)
 for name, group in groupby(sorted(a_list, key=key), key)}

这是一种 O(NlogN) 方法与直接的 O(N) 方法相比,没有排序的循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多