在python的list函数中返回max number

2024-04-20 09:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如何返回最大匹配数?例如:

def maximum_number([4, 5, 6, 5, 2])

返回2,因为5是最大值,出现两次。你知道吗


Tags: numberdefmaximum
3条回答

如图所示,使用计数器非常有效。然而,这无助于理解这种模式。所以这里有一个手工制作的方法

  1. 创建一个空的dict
  2. 循环输入//列表
  3. 在dict中找到这个值作为键
    • 如果存在,则将值增加1
    • 否则将其相加,值为1

循环完成后,在dict中找到最高值并使用其键

所有这些都可以在Python中有效地完成,使用dict.get(key, 0)+1dict.iteritems()(对于Python-2;items(),对于Python-3)。你知道吗

将您的列表放入^{} object并要求它给出最重要的结果:

from collections import Counter

def maximum_number(lst):
    return Counter(lst).most_common(1)[0][1]

^{} method按count返回前N个结果;上面的代码要求返回前1个结果,从返回的列表中获取该结果并仅提取count:

>>> from collections import Counter
>>> lst = [4, 5, 6, 5, 2]
>>> Counter(lst)
Counter({5: 2, 2: 1, 4: 1, 6: 1})
>>> Counter(lst).most_common(1)
[(5, 2)]
>>> Counter(lst).most_common(1)[0]
(5, 2)
>>> Counter(lst).most_common(1)[0][1]
2

这可以帮你。。你知道吗

lst = [4, 5, 6, 5, 2]    
max([lst.count(i) for i in lst])

相关问题 更多 >