gpt4 book ai didi

python - 试图在列表中找到多数元素

转载 作者:IT老高 更新时间:2023-10-28 21:16:24 25 4
gpt4 key购买 nike

我正在编写一个函数来查找 Python 列表中的多数。

想如果我可以编写一个散列函数,可以将每个元素映射到新数组中的单个槽或唯一标识符,也许对于字典,那应该是最好的,它应该是可撤销的。我不知道如何进步。我的哈希函数显然没用,关于我可以/应该做什么的任何提示,或者这是否是一种合理的方法?

def find_majority(k):
def hash_it(q):
return q

map_of = [0]*len(k)

for i in k:
mapped_to = hash_it(i) #hash function
map_of[mapped_to]+=1


find_majority([1,2,3,4,3,3,2,4,5,6,1,2,3,4,5,1,2,3,4,6,5])

最佳答案

Python 有一个名为 Counter 的内置类会为您执行此操作。

>>> from collections import Counter
>>> c = Counter([1,2,3,4,3,3,2,4,5,6,1,2,3,4,5,1,2,3,4,6,5])
>>> c.most_common()
[(3, 5), (2, 4), (4, 4), (1, 3), (5, 3), (6, 2)]
>>> value, count = c.most_common()[0]
>>> print value
3

查看文档。

http://docs.python.org/2/library/collections.html#collections.Counter

关于python - 试图在列表中找到多数元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038011/

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