gpt4 book ai didi

Python:列表中出现次数最多的值

转载 作者:太空狗 更新时间:2023-10-29 17:37:15 27 4
gpt4 key购买 nike

我有两个列表如下

x = ['a','a','b','c','b','a']

x = ['a','a','b','c','c','d']

我试图找出每个列表中出现次数最多的值。这是我试过的。

def unique_values(output,input):
for i in input:
if i not in output:
output.append(i)
k = []
for i in k:
unique_values(k,x)
y.remove(i)

我已经走到这一步了,但我不知道如何在 for i in k: 删除列表中的所有值之前停止它。

最佳答案

如果你想找到列表中每个元素的出现次数,你可以使用 collections 中的 Counter 模块:-

>>> x = ['a','a','b','c','c','d']

>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

因此,前两个元素在您的列表中最常见。

>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)

或者,您还可以将参数传递给 most_common() 以指定您想要多少个 most_common 元素:-

>>> count.most_common(2)
[('a', 2), ('c', 2)]

更新:-

也可以先求出max的个数,然后求出该值的元素总数,然后就可以在most_common()中作为参数使用:-

>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)

>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]

>>> [elem[0] for elem in most_common]
['a', 'c']

关于Python:列表中出现次数最多的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13707457/

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