要使用字典理解做你想做的事,你需要一个外部 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) 方法相比,没有排序的循环。