Python - returns the largest of N lists

I would like the function to return the largest of the N-list. With two items on 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 lots of lists, it becomes a sequence of if statements, and it is ugly.

How would you very effectively return the largest of N lists?

+6
source share
1 answer

Use max with key=len .

 In [3]: max([l1, l2], key=len) Out[3]: [4, 5, 6, 7] 

This will result in a (first) long list for the list of lists.

In fact, this will also work with strings (and other objects with the 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 elements as arguments:

 In [7]: max(l1, l2, key=len) Out[7]: [4, 5, 6, 7] 

max reads: get me the largest element in the list when (if you pass key ) looking from the point of view of key .
This is roughly equivalent to the following code * (in python 3), but the actual source is written in C (much more efficient, and in fact, please continue to use max, not that!):

 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 this as an exercise to write it using iterators, not lists ... and fix any other errors!

+28
source

Source: https://habr.com/ru/post/945722/


All Articles