This question already has an answer here:
这个问题已经有了答案:
- How to find duplicate elements in array using for loop in Python? 15 answers
- 如何在Python中使用for循环查找数组中的重复元素?15个答案
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
5 个解决方案
#1
29
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}
Or using collections.Counter
:
或者使用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}
#2
6
Use Counter
使用计数器
>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})
#3
3
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}
#4
0
yourList = ["a", "b", "a", "c", "c", "a", "c"]
expected outputs {a: 3, b: 1,c:3}
期望输出{a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
duplicateFrequencies[i] = yourList.count(i)
Cheers!! Reference
干杯! !参考
#5
0
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}
#1
29
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}
Or using collections.Counter
:
或者使用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}
#2
6
Use Counter
使用计数器
>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})
#3
3
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}
#4
0
yourList = ["a", "b", "a", "c", "c", "a", "c"]
expected outputs {a: 3, b: 1,c:3}
期望输出{a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
duplicateFrequencies[i] = yourList.count(i)
Cheers!! Reference
干杯! !参考
#5
0
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}