2013-05-23 13 views
6

Vorrei che una funzione restituisca il più grande dell'elenco N. Con due elementi nell'elenco posso scrivere:Python - restituisce il numero più grande di N liste

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] 

che corro con f([l1, l2]).

Tuttavia, con più elenchi, diventa una successione di istruzioni if, ed è brutto.

Come restituire in modo efficiente il più grande di N elenchi?

risposta

28

Utilizzare max con key=len.

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

Questo sarà recuperare la (prima) lista più lunga, per una lista di liste.

In effetti, questo funzionerà anche con le stringhe (e altri oggetti con un attributo len).

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' 

Nota: possiamo anche passare nelle voci come argomenti:

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

max legge: mi porti l'elemento più grande nella lista quando (se si passa key), guardando dal punto di vista di key.
E 'grosso modo equivalente al seguente codice * (in Python 3), ma la fonte reale è written in C (così molto più efficiente, così come in realtà testato, quindi si prega di continuare a utilizzare massimo e non questo!):

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 

* Lascio come esercizio scrivere questo usando gli iteratori anziché le liste ... e correggere eventuali altri bug!

+0

Wow, non sapevo di quella funzione. Eccezionale! – Mezgrman

+0

questo è davvero un ottimo modo –

Problemi correlati