user483144
user483144

Reputation: 1441

Python: Sorting this list

`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

Upvotes: 1

Views: 127

Answers (3)

tzot
tzot

Reputation: 95931

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.

Upvotes: 1

Klark
Klark

Reputation: 8280

>>> 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().

Upvotes: 2

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

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

Upvotes: 2

Related Questions