views:

51

answers:

3
`li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]`

I want to sort li depending on the first number in each element eg.1106257, 1, 1,1,9,1,406

How to do this fast? Thanks

+2  A: 

have you tried li.sort() or sorted(li)?

TokenMacGuy
+2  A: 
>>> li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]
>>> li.sort()
>>> li
[(1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (1, (64, 64, 126)), (9, (249, 249, 249)), (406, (247, 247, 251)), (1106257, (255, 255, 255))]

Default behavior when comparing tuples is to compare first the first one, then the second one etc. You can override this by giving a custom compare function as argument to the sort().

Klark
Don't use custom compare functions. They're slow and not supported in Python 3. Use key functions instead.
adw
+1  A: 

What you ask is the default behaviour when comparing tuples. However, the generic answer to your question can be:

>>> import operator

>>> li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]
>>> li.sort(key=operator.itemgetter(0))
>>> li
[(1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (1, (64, 64, 126)),
 (9, (249, 249, 249)), (406, (247, 247, 251)), (1106257, (255, 255, 255))]

If you want to sort based on columns other than the first (0), change that number. For example, if you want to sort based on columns 2 then 1, you would provide operator.itemgetter(2, 1) as key.

ΤΖΩΤΖΙΟΥ