Skip to main content
 首页 » 编程设计

python字典理解迭代器

2025年05月04日8yjmyzz

嘿,我对我写的以下 python 代码有疑问:

#create a list of elements 
#use a dictionary to find out the frequency of each element 
list = [1,2,6,3,4,5,1,1,3,2,2,5] 
list.sort() 
dict = {i: list.count(i) for i in list} 
print(dict) 

在字典压缩方法中,“for i in list”是提供给方法的顺序吗?所以它需要 1,2,3,4.. 作为键。我的问题是为什么不需要 1 三次?因为我已经说过“for i in list”,所以它不是必须将列表中的每个元素都作为键吗?

(我是 python 的新手,所以对我放轻松!)

请您参考如下方法:

My question is why doesn't it take 1 three times ?

那是因为字典键是唯一的。如果为同一键找到另一个条目,则该键的先前值将被覆盖。

好吧,对于你的问题,如果你只是在计算列表中每个元素的频率之后,那么你可以使用 collections.Counter

请不要使用 list 作为变量名。它是内置的。

>>> lst = [1,2,6,3,4,5,1,1,3,2,2,5] 
>>> from collections import Counter 
>>> Counter(lst) 
Counter({1: 3, 2: 3, 3: 2, 5: 2, 4: 1, 6: 1})