1

嘿,作为新手,我想知道如何从列表中找到多个最大值(即有多个最大值或相同长度的项目)和最小值(与最大值相同的位置)。我尝试使用该max功能,但它只打印一项,与min. 它是针对列表中字符串的长度来完成的(例如使用len)!

这是我到目前为止的代码

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

4 回答 4

5

试试这个:

def 选择4(文件列表):
    mymax = max(map(len,filelist))
    return [a for a in filelist if len(a)==mymax]

a = ['乔','安迪','马克','史蒂夫']
a.扩展(一)
打印选择4(a)
于 2013-01-24T18:54:28.817 回答
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根据需要构建和替换where以仅保存最长的元素:

>>> 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']
于 2013-01-24T18:53:34.340 回答
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']
于 2013-01-24T18:53:18.277 回答
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
于 2015-01-15T20:25:53.847 回答