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

时间:2014-04-23 10:00:58

标签: python python-2.7

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

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

输出:

a: 3
b: 1
c: 3

5 个答案:

答案 0 :(得分:49)

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

答案 1 :(得分:8)

使用Counter

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

答案 2 :(得分:4)

这适用于Python 2.6.6

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

打印

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

答案 3 :(得分:2)

lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
    result[i]=lst.count(i)
print result

输出:

{'a': 3, 'c': 3, 'b': 1}

答案 4 :(得分: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)

干杯!! Reference