Charlie Hardy
Charlie Hardy

Reputation: 305

multiple maximums in a list python

Hey so being the NEWBY I am I was wondering how I could find multiple maximums (i.e. there is more than one maximum or item of the same length) and minimums(same situ as maximums) from a list. I've tried using the max function but yet it prints only one item, same with min. It is to be done for length of the string in the list (e.g. usinglen)!

this is the code i had so far

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

Upvotes: 1

Views: 10769

Answers (4)

ifmihai
ifmihai

Reputation: 89

use 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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124818

You could use sorting instead:

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

which takes O(n log n) time for the sort; but it's easy and short as the longest elements are all at the start for easy picking.

For a O(n) solution use a loop:

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

where maxlist is built and replaced as needed to hold only the longest elements:

>>> 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']

Upvotes: 2

Steve Peak
Steve Peak

Reputation: 2677

Try this:

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)

Upvotes: 5

Lev Levitsky
Lev Levitsky

Reputation: 65851

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']

Upvotes: 0

Related Questions