Python: 计算列表中的重复元素

我是巨蟒的新手。我试图找到一个简单的方法来计算一个列表中重复的元素的数量,例如。

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

产出:

a: 3
b: 1
c: 3
312601 次浏览

你可以使用 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}
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)

干杯! ! 参考文献

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}

使用 Counter

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

这适用于 Python 2.6.6

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

指纹

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