gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:35:44 29 4
gpt4 key购买 nike

我是 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}

使用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}

关于Python:计算列表中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23240969/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com