gpt4 book ai didi

python - 列表中频率最高的数字

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:34 26 4
gpt4 key购买 nike

我正在尝试编写一个程序来显示列表中出现频率最高的数字。我试图在不导入任何库的情况下执行此操作。到目前为止,我有一些东西可以给我最频繁的#出现次数,但我想要数字本身,而不是它出现的次数。我怎样才能以一种简单的方式改变我目前拥有的东西来做到这一点?

def freq(L):
st = []
L.sort()
for i in L:
st.append(L.count(i))
print max(st)

编辑:例如,freq([4, 6, 4, 3, 9, 1, 4]) 返回 3,因为 4 出现了 3 次。但我希望它以最常见的值返回 4。

最佳答案

尝试字典

def freq(L):
st = {}
for i in set(L):
st.update({L.count(i):i})
print (st.get(max(st)))

或更短:

def freq(L):
st={L.count(i):i for i in set(L)}
print (st.get(max(st)))

另一种没有字典的解决方案:

def freq(L):
a=0
b=None
for e in set(L):
if L.count(e)>a:
a=L.count(e)
b=e
print(b)

关于python - 列表中频率最高的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52194235/

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