Python:计算列表中重复的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23240969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:34:24 来源:igfitidea点击:
Python: count repeated elements in the list
提问by Jojo
I am new to Python. I am trying to find a simple way of getting a count of the number of elements repeated in a list e.g.
我是 Python 的新手。我试图找到一种简单的方法来计算列表中重复元素的数量,例如
MyList = ["a", "b", "a", "c", "c", "a", "c"]
Output:
输出:
a: 3
b: 1
c: 3
采纳答案by sshashank124
You can do that using count
:
你可以使用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}
Orusing 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}
回答by Daniel Adenew
回答by Nishant Nawarkhede
lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
result[i]=lst.count(i)
print result
Output:
输出:
{'a': 3, 'c': 3, 'b': 1}
回答by Jayanth Koushik
Use Counter
用 Counter
>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})
回答by Peter Kelly
This works for Python 2.6.6
这适用于 Python 2.6.6
a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result
prints
印刷
{'a': 2, 'b': 1}