python - Python中的惯用,线性时间,计数字典
问题描述
我有一些清单:
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
or 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}
>>>
推荐阅读
- c++ - 我可以在这里避免沮丧吗?
- bash - 如何在同一个文件中按顺序搜索多个字符串?
- typescript - 推断打字稿嵌套的泛型类型
- javascript - React Native,在选项卡导航器中按下选项卡时如何将参数传递到屏幕?
- iframe - iframe 在某些浏览器中正确加载网页,但在其他浏览器中不正确(不安全的内容错误)
- c# - Unity - 如果与子对象发生碰撞,如何锚定到对象
- python - 定义k-1个簇质心——SKlearn KMeans
- python - 位置参数跟随关键字 - menubar.add_cascade(label = "File", menu.filemenu) - 计算器
- javascript - TypeError:records.map 不是反应中的函数
- php - PHP - 将多个数组相互组合