This question already has answers here:
Count frequency of words in a list and sort by frequency
(12个答案)
2年前关闭。
我有一些清单:
我想把它变成字典,其中的关键是水果,值是它在列表中出现的次数。
该列表可能会很大,因此将其设为线性时间会很好。
用冗长的方式很容易做到这一点:
显然这是O(n)时间,但是感觉我应该可以通过字典理解来做到这一点。
我唯一能想到的事情是涉及多次调用
有人可以指出一种更“ pythonic”的方法来执行此操作(我想这涉及理解),还是应该保留上面的详细实现?
而且也很容易转换回:
如果想要一个字典:
顺便说一句,不要为任何现有对象(现在为
或另一种方式是:
(12个答案)
2年前关闭。
我有一些清单:
list = ["apple", "orange", "orange", "apple", "grape"]
我想把它变成字典,其中的关键是水果,值是它在列表中出现的次数。
该列表可能会很大,因此将其设为线性时间会很好。
用冗长的方式很容易做到这一点:
from collections import DefaultDict
dict_of_counts = DefaultDict(int)
for item in list:
dict_of_counts[item] += 1
显然这是O(n)时间,但是感觉我应该可以通过字典理解来做到这一点。
我唯一能想到的事情是涉及多次调用
len
或count
,因此这将是O(kn)时间(其中k是列表中键的不同数目)。有人可以指出一种更“ pythonic”的方法来执行此操作(我想这涉及理解),还是应该保留上面的详细实现?
最佳答案
使用Counter
:
>>> from collections import Counter
>>> l = ["apple", "orange", "orange", "apple", "grape"]
>>> Counter(l)
Counter({'apple': 2, 'orange': 2, 'grape': 1})
>>>
而且也很容易转换回:
>>> c=Counter(l)
>>> list(c.elements())
['apple', 'apple', 'orange', 'orange', 'grape']
>>>
如果想要一个字典:
>>> dict(c)
{'apple': 2, 'orange': 2, 'grape': 1}
>>>
顺便说一句,不要为任何现有对象(现在为
list
)命名变量或另一种方式是:
>>> {i:l.count(i) for i in l}
{'apple': 2, 'orange': 2, 'grape': 1}
>>>