python字典理解迭代器 [英] python dictionary comprehension iterator
问题描述
创建一个元素列表
#使用一个字典来查找每个元素的频率
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 ..作为关键。我的问题是为什么不需要三次?因为我已经说我在列表中,它不需要把列表中的每一个元素作为一个键?
(我是新的对于python这么容易我!)
是的,你的怀疑是正确的。 1
将在迭代中出现3次。然而,由于词典具有唯一的键,所以每次 1
出现时,它将替换以前生成的键/值对与新生成的键/值对。这将给出正确的答案,这不是最有效率的。您可以将列表转换为一个集合,以避免重新处理重复的密钥:
dict = {i:list.count(i)对于我在set(列表)}
但是,即使这种方法是非常低效的,因为它完全通过列表中每个值的列表,即O(n²)总比较。你可以在列表中单次通过,但是你不会使用dict的理解:
xs = [1 ,2,6,3,4,5,1,1,3,2,2,5]
计数= {}
x中的x:
计数[x] =计数.get(x,0)+ 1
的结果计数
是:
{1:3,2:3,3:2,4:1,5:2,6:1}
编辑:我没有意识到图书馆里有什么可以为你做这件事。您应该使用Rohit Jain的解决方案,使用 collections.Counter
。
Hey I have a doubt in the following python code i wrote :
#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)
In the dictionary compression method, "for i in list" is the sequence supplied to the method right ? So it takes 1,2,3,4.. as the keys. My question is why doesn't it take 1 three times ? Because i've said "for i in list", doesn't it have to take each and every element in the list as a key ?
(I'm new to python so be easy on me !)
Yes, your suspicion is correct. 1
will come up 3 times during iteration. However, since dictionaries have unique keys, each time 1
comes up it will replace the previously generated key/value pair with the newly generated key/value pair. This will give the right answer, it's not the most efficient. You could convert the list to a set instead to avoid reprocessing duplicate keys:
dict = {i: list.count(i) for i in set(list)}
However, even this method is horribly inefficient because it does a full pass over the list for each value in the list, i.e. O(n²) total comparisons. You could do this in a single pass over the list, but you wouldn't use a dict comprehension:
xs = [1,2,6,3,4,5,1,1,3,2,2,5]
counts = {}
for x in xs:
counts[x] = counts.get(x, 0) + 1
The result for counts
is: {1: 3, 2: 3, 3: 2, 4: 1, 5: 2, 6: 1}
Edit: I didn't realize there was something in the library to do this for you. You should use Rohit Jain's solution with collections.Counter
instead.
这篇关于python字典理解迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!