Python: 统计列表中重复元素的个数

85

我是Python的新手。我正在尝试找到一种简单的方法来计算列表中重复元素的数量,例如:

MyList = ["a", "b", "a", "c", "c", "a", "c"]

输出:

a: 3
b: 1
c: 3
5个回答

201
你可以使用count来实现这一点:
my_dict = {i:MyList.count(i) for i in MyList}

>>> print my_dict     #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

或者使用collections.Counter


from collections import Counter

a = dict(Counter(MyList))

>>> print a           #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

第一种选项导致语法错误。 - Peter Kelly
2
在Python 3中会引发语法错误(print是一个函数),但在2.7中可以正常工作。 - jabaldonedo
4
这个解决方案非常缓慢。使用pandas可以快得多:pd.DataFrame(MyList, columns=["x"]).groupby('x').size().to_dict() - Make42
我从来没有像找到这个答案一样开心过!完美地解决了我的问题。6年后仍然一样新鲜 :) - BrettJ
3
如果在“for”循环中使用“set”来获取唯一值,速度会更快: setList = list(set(Mylist)) my_dict = {i:MyList.count(i) for i in setList} - Eduardo Bocarruido
显示剩余5条评论

26

使用 Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

12

这适用于Python 2.6.6。

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

打印

{'a': 2, 'b': 1}

1
与旧版本兼容,加1。 - sshashank124

7
yourList = ["a", "b", "a", "c", "c", "a", "c"]

期望输出 {a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
    duplicateFrequencies[i] = yourList.count(i)

干杯!! 参考


7
In [2]: MyList = ["a", "b", "a", "c", "c", "a", "c"]

In [3]: count = {}

In [4]: for i in MyList:
   ...:     if not i in count:
   ...:         count[i] = 1
   ...:     else:
   ...:         count[i] +=1
   ...:

In [5]: count
Out[5]: {'a': 3, 'b': 1, 'c': 3}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接