具有键列表的快速字典填充

Hen*_*ton 1 python dictionary list

d = {} # or d = defaultdict(int)

list_of_lists = [[9, 7, 5, 3, 1], [2, 1, 3, 2, 5, 3, 7], [3, 5, 8, 1]]

for lst in list_of_lists:
    for key in lst:
        try:
            d[key] += 1
        except:
            d[key] = 1
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有for循环的情况下执行此操作?

Mar*_*ers 7

使用collections.Counter()对象和生成器表达式:

from collections import Counter

d = Counter(i for nested in list_of_lists for i in nested)
Run Code Online (Sandbox Code Playgroud)

或用以下代替生成器表达式itertools.chain.from_iterable():

from itertools import chain

d = Counter(chain.from_iterable(list_of_lists))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> from collections import Counter
>>> from itertools import chain
>>> list_of_lists = [[9, 7, 5, 3, 1], [2, 1, 3, 2, 5, 3, 7], [3, 5, 8, 1]]
>>> Counter(i for nested in list_of_lists for i in nested)
Counter({3: 4, 1: 3, 5: 3, 2: 2, 7: 2, 8: 1, 9: 1})
>>> Counter(chain.from_iterable(list_of_lists))
Counter({3: 4, 1: 3, 5: 3, 2: 2, 7: 2, 8: 1, 9: 1})
Run Code Online (Sandbox Code Playgroud)