我是Python的新手。我试图找到一种简单的方法来获取列表中重复的元素数量的计数,例如
MyList = ["a", "b", "a", "c", "c", "a", "c"]
输出:
a: 3
b: 1
c: 3
您可以使用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}
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句