I would like have a function return the largest of N list. With two items in the list I can write:
l1 = [3, 4, 5]
l2 = [4, 5, 6, 7]
def f(L):
if(len(L[0]) > len(L[1])):
return L[0]
else:
return L[1]
which I run with f([l1, l2])
.
However, with more lists, it becomes a succession of if statements, and it is ugly.
How would you very efficiently return the largest of N lists ?
Use max
with key=len
.
In [3]: max([l1, l2], key=len)
Out[3]: [4, 5, 6, 7]
This will retrieve the (first) longest list, for a list of lists.
In fact, this will also work with strings (and other objects with a len attribute).
In [4]: max(['abcd', 'ab'], key=len)
Out[4]: 'abcd'
In [5]: max([(1, 2), (1, 2, 3), (1,)], key=len)
Out[5]: (1, 2, 3)
In [6]: max(['abc', [1, 2, 3]], key=len)
Out[6]: 'abc'
Note: we can also pass in the items as arguments:
In [7]: max(l1, l2, key=len)
Out[7]: [4, 5, 6, 7]
max
reads: get me the largest item in the list when (if you pass key
) looking from the perspective of key
.
It's roughly equivalent to the following code* (in python 3) but the actual source is written in C (so much more efficient, as well as actually tested, so please continue to use max and not this!):
def my_max(*L, key=None): # in python 2 we'd need to grab from kwargs (and raise type error if rogue keywords are passed)
L = list(L[0]) if len(L) == 1 else L # max takes iterable as first argument, or two or more arguments...
if not L:
raise ValueError("my_max() arg is an empty sequence")
if key is None: # if you don't pass a key use the identity
key = lambda x: x
max_item, max_size = L[0], key(L[0])
for item in L[1:]:
if key(item) > max_size:
max_item, max_size = item, key(item)
return max_item
*I leave it as an exercise to write this using iterators rather than lists... and fix any other bugs!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.