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 depen开发者_如何学运维ding on the first number in each element eg.1106257, 1, 1,1,9,1,406
How to do this fast? Thanks
have you tried li.sort()
or sorted(li)
?
>>> 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().
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
.
精彩评论