Skip to main content
 首页 » 编程设计

python之带有键列表的快速字典填充

2025年05月04日16bonelee

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 

有没有办法不用 for 循环来执行这个操作?

请您参考如下方法:

使用 collections.Counter() object和一个生成器表达式:

from collections import Counter 
 
d = Counter(i for nested in list_of_lists for i in nested) 

或者用 itertools.chain.from_iterable() 替换生成器表达式:

from itertools import chain 
 
d = Counter(chain.from_iterable(list_of_lists)) 

演示:

>>> 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})