Sorting (deeply) nested lists

Peter Otten __peter__ at web.de
Sat Mar 2 18:36:43 CET 2013


mamboknave at gmail.com wrote:

> I cannot resolve this on my own. Need help, please...
> 
> nestedTuples = [
> [ (L0t0e0, L0t0e1, L0t0e2), (L0t1e0, 2, L0t1e2), (L0t2e0, L0t2e1, L0t2e2)
> [ ], (L1t0e0, L1t0e1, L1t0e2), (L1t1e0, 0, L1t1e2), (L1t2e0, L1t2e1,
> [ L1t2e2) ], (L2t0e0, L2t0e1, L2t0e2), (L2t1e0, 1, L2t1e2), (L2t2e0,
> [ L2t2e1, L2t2e2) ] ]
> 
> With LNtXeY I mean the element Y in the tuple X of the list N.
> 
> How can I sort nestedTuples by, say, the 2nd element in the 2nd tuple of
> each list?

def getkey(item):
    return item[1][1]
namedTuples.sort(key=getkey)

You can also write this as

namedTuples.sort(key=lambda item: item[1][1])

> The above should get sorted as :
> 
> nestedTuples = [
> [ (L1t0e0, L1t0e1, L1t0e2), (L1t1e0, 0, L1t1e2), (L1t2e0, L1t2e1, L1t2e2)
> [ ], (L2t0e0, L2t0e1, L2t0e2), (L2t1e0, 1, L2t1e2), (L2t2e0, L2t2e1,
> [ L2t2e2) ], (L0t0e0, L0t0e1, L0t0e2), (L0t1e0, 2, L0t1e2), (L0t2e0,
> [ L0t2e1, L0t2e2) ] ]





More information about the Python-list mailing list