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

use*_*527 23 python python-2.7

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

MyList = ["a", "b", "a", "c", "c", "a", "c"]
Run Code Online (Sandbox Code Playgroud)

输出:

a: 3
b: 1
c: 3
Run Code Online (Sandbox Code Playgroud)

ssh*_*124 56

你可以这样做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}
Run Code Online (Sandbox Code Playgroud)

使用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}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案超级慢。使用熊猫要快得多:`pd.DataFrame(MyList, columns=["x"]).groupby('x').size().to_dict()` (3认同)
  • 如果您使用“set”来获取“for”中的唯一值,那么速度会更快:`setList = list(set(Mylist)) my_dict = {i:MyList.count(i) for i in setList}` (3认同)
  • 它在 Python 3 中引发语法错误(print 是一个函数),它在 2.7 中有效。 (2认同)

Jay*_*hik 10

使用 Counter

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


dan*_*lad 7

yourList = ["a", "b", "a", "c", "c", "a", "c"]
Run Code Online (Sandbox Code Playgroud)

预期输出 {a: 3, b: 1,c:3}

duplicateFrequencies = {}
for i in set(yourList):
    duplicateFrequencies[i] = yourList.count(i)
Run Code Online (Sandbox Code Playgroud)

干杯!!参考


Nis*_*ede 5

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}
Run Code Online (Sandbox Code Playgroud)


Pet*_*lly 5

这适用于Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result
Run Code Online (Sandbox Code Playgroud)

版画

{'a': 2, 'b': 1}
Run Code Online (Sandbox Code Playgroud)