2010-08-16 73 views
96

我是新来的Python和我有一个简单的问题,说我有一个项目列表:的Python:使用字典来算列表中的项目

['apple','red','apple','red','red','pear'] 

请告诉我simpliest方式来添加将项目列入词典并计算项目在列表中出现的次数。所以

的名单上面,我想输出是:

{'apple': 2, 'red': 3, 'pear': 1} 
+1

,你可以在这里得到启示:HTTP ://stackoverflow.com/questions/2870466/python-histogram-one-liner – mykhal 2010-08-16 19:23:41

+0

http://stackoverflow.com/questions/13242103/how-to-compute-letter-frequency-in-a-string-using-pythons -build-in-map-and-reduc – 2015-08-16 08:47:12

+0

有没有人注意到输出的顺序?这是不相干的吗? – 2016-06-18 18:50:33

回答

46
>>> 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}) 
+2

可能是最快和最杂乱的方法。 – 2010-08-16 19:28:56

3
L = ['apple','red','apple','red','red','pear'] 
d = {} 
[d.__setitem__(item,1+d.get(item,0)) for item in L] 
print d 

给人{'pear': 1, 'apple': 2, 'red': 3}

170

在2.7和3.1有特殊Counter字典用于这一目的。

>>> from collections import Counter 
>>> Counter(['apple','red','apple','red','red','pear']) 
Counter({'red': 3, 'apple': 2, 'pear': 1}) 
+11

Yuck;已经足够的Python库中的狭义用途了。 – 2010-08-16 20:27:21

+2

圭多有一个时间机器官方的线,或相当长久的笑话。 – 2010-08-17 00:04:56

+8

@Glenn Maynard计数器只是一个** multiset **的实现,它不是一个不常见的数据结构国际海事组织。事实上,C++在STL中有一个名为'std :: multiset'(也是'std :: tr1 :: unordered_multiset')的实现,所以Guido并不孤单。 – awesomo 2011-10-18 03:07:34

11

我一直认为对于一个微不足道的任务,我不想导入任何东西。但我可能是错误的,取决于collections.Counter是否更快或不。

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)) 

我想这可能是最好使用count(),因为它只会走在迭代一次,而指望可以搜索在每次迭代的整个事情。我使用这种方法来解析许多兆字节的统计数据,并且总是相当快速。

+1

您的答案值得更多因为它很简单,我一直在为此苦苦挣扎,一些其他用户的愚蠢暗示会导入新的库等。 – ntk4 2016-09-23 05:56:17

92

我喜欢:

counts = dict() 
for i in items: 
    counts[i] = counts.get(i, 0) + 1 

不用彷徨让你如果键不存在,指定一个默认值。

+6

对于那些新的python。这个答案在时间复杂性方面更好。 – curiousMonkey 2016-04-18 05:07:45

+0

这个答案即使在浮点数的列表中也适用,其中一些数字可能为'0' – SherylHohman 2017-05-03 05:12:53

6

如何:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ] 
result_dict = dict([ (i, src.count(i)) for i in set(src) ]) 

这导致

{ '一':1, '三化':3, '两节':2}

+7

注意这是由于对'src.count()的'n'调用引起的'O(n^2)'。 – dimo414 2014-02-17 20:22:03

23

只需使用列表属性计数\

i = ['apple','red','apple','red','red','pear'] 
d = {x:i.count(x) for x in i} 
print d 

输出:{ '梨':1, '苹果':2, '红色':3}

+2

虽然它起作用,但这似乎效率不高。 – Ouroborus 2017-09-27 17:41:18

+0

你可以详细说明吗? – 2017-11-28 08:59:36

+0

你正在对数组应用'count'多次有数组项目。你的解决方案是'O(n^2)',更好的解决方案是'O(n)'。请参阅[riviera的回答](https://stackoverflow.com/a/9604768/367865)上的评论与[mmdreg的回答](https://stackoverflow.com/a/6582852/367865)上的评论。 – Ouroborus 2017-11-29 09:50:05