我是Python的新手,我有一个简单的问题,比如我有一个项目列表:
['apple','red','apple','red','red','pear']
Run Code Online (Sandbox Code Playgroud)
什么是将列表项添加到字典中的最简单方法,并计算项目在列表中出现的次数.
所以对于上面的列表,我希望输出为:
{'apple': 2, 'red': 3, 'pear': 1}
Run Code Online (Sandbox Code Playgroud)
Odo*_*ois 248
在2.7和3.1中有一个特殊的Counter
字典用于此目的.
>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})
Run Code Online (Sandbox Code Playgroud)
mmm*_*reg 176
我喜欢:
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
Run Code Online (Sandbox Code Playgroud)
如果密钥不存在,.get允许您指定默认值.
ber*_*nie 55
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
... d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
Run Code Online (Sandbox Code Playgroud)
Ash*_*rma 39
只需使用列表属性计数
i = ['apple','red','apple','red','red','pear']
d = {x:i.count(x) for x in i}
print d
Run Code Online (Sandbox Code Playgroud)
输出:
{'pear': 1, 'apple': 2, 'red': 3}
Run Code Online (Sandbox Code Playgroud)
Ste*_*zzo 18
我一直认为,对于一项微不足道的任务,我不想进口任何东西.但我可能是错的,取决于收藏.对比更快或更快.
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
Run Code Online (Sandbox Code Playgroud)
我认为这可能比使用count()更可取,因为它只会超过迭代次数,而count可以在每次迭代时搜索整个事物.我使用这种方法来解析许多兆字节的统计数据,而且总是相当快.
考虑collections.Counter(可从python 2.7开始). https://docs.python.org/2/library/collections.html#collections.Counter
这个怎么样:
src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )
Run Code Online (Sandbox Code Playgroud)
这导致了
{'one':1,'three':3,'two':2}
L = ['apple','red','apple','red','red','pear']
d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in L]
print d
Run Code Online (Sandbox Code Playgroud)
给予{'pear': 1, 'apple': 2, 'red': 3}
归档时间: |
|
查看次数: |
204437 次 |
最近记录: |