假设我有一个清单:
a_list = [["Bob", 2], ["Bill", 1], ["Bob", 2]]
我想将这些添加到字典中并将值组合到相应的键中。所以,在这种情况下,我想要一个看起来像这样的字典:
{"Bob" : 4, "Bill" : 1}
我怎么能用字典理解来做到这一点?
这就是我所拥有的:
d1 = {group[0]: int(group[1]) for group in a_list}
假设我有一个清单:
a_list = [["Bob", 2], ["Bill", 1], ["Bob", 2]]
我想将这些添加到字典中并将值组合到相应的键中。所以,在这种情况下,我想要一个看起来像这样的字典:
{"Bob" : 4, "Bill" : 1}
我怎么能用字典理解来做到这一点?
这就是我所拥有的:
d1 = {group[0]: int(group[1]) for group in a_list}
要使用字典理解做你想做的事,到目前为止,你需要一个外部额外的字典来跟踪每个名称的值:
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()
对象:
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) 方法。