首页 > 解决方案 > 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) 时间,但感觉我应该能够通过字典理解来做到这一点。我唯一能想到的事情涉及多次调用lenor count,所以这将是 O(kn) 时间(其中 k 是我列表中不同的键数)。

有人可以指出一种更“pythonic”的方式来做到这一点(我想这涉及理解),还是我应该保持上面的冗长实现?

标签: pythonpython-3.xidioms

解决方案


使用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}
>>>

推荐阅读