列表python中的多个最大值

时间:2013-01-24 18:50:52

标签: python list max minimum

嘿,所以我是NEWBY我想知道如何从列表中找到多个最大值(即,存在多个相同长度的最大值或项目)和最小值(与最大值相同)。我尝试过使用max函数,但它只打印了一个项目,与min相同。要对列表中的字符串长度进行处理(例如使用len)!

这是我到目前为止的代码

    def choice4(filelist):
       try:
           c4longest=max(filelist,key=len)
           print(c4longest,"is the longest item in the list")

4 个答案:

答案 0 :(得分:5)

试试这个:

def choice4(filelist):
    mymax = max(map(len,filelist))
    return [a for a in filelist if len(a)==mymax]

a = ['joe','andy','mark','steve']
a.extend(a)
print choice4(a)

答案 1 :(得分:2)

您可以改为使用排序:

maxed = sorted(inputlist, key=lambda i: len(i), reverse=True)
allmax = list(takewhile(lambda e: len(e) == len(maxed[0]), maxed))

需要O(n log n)次排序;但它很简单,因为最长的元素都是易于采摘的开始。

对于O(n)解决方案,请使用循环:

maxlist = []
maxlen = 0
for el in inputlist:
    l = len(el)
    if l > maxlen:
       maxlist = [el]
       maxlen = l
    elif l == maxlen:
       maxlist.append(el)

其中构建maxlist并根据需要替换以仅保留最长的元素:

>>> inputlist = 'And so we give a demo once more'.split()
>>> maxlist = []
>>> maxlen = 0
>>> for el in inputlist:
...     l = len(el)
...     if l > maxlen:
...        maxlist = [el]
...        maxlen = l
...     elif l == maxlen:
...        maxlist.append(el)
... 
>>> maxlist
['give', 'demo', 'once', 'more']

答案 2 :(得分:0)

In [1]: l = 'Is that what you mean'.split()

In [2]: [word for word in l if len(word) == max(map(len, l))]
Out[2]: ['that', 'what', 'mean']

答案 3 :(得分:0)

使用collections.Counter

from collections import Counter
d = Counter({k:v for k,v in enumerate(L)})
print d.most_common(5)  # to get top 5