1
`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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.