python - How to sort tuple twice -
for example,
a = [(4, 3), (6, 3), (2, 1), (3, 1)]
how sort tuple twice without using itemgetter
? want sort first key = a[1]
, second key = a[0]
. this,
a = [(6, 3), (4, 3), (3, 1), (2, 1)]
just reverse sort:
sorted(a, reverse=true)
for new list or
a.sorted(reverse=true)
to sort list in-place.
tuples compared lexicographically, first first element, second in case of tie. sorting first second element, first, result in exactly same order if first sorted second element , sorted resulting list first:
>>> operator import itemgetter >>> = [(4, 3), (6, 3), (2, 1), (3, 1)] >>> sorted(a, key=itemgetter(1), reverse=true) [(4, 3), (6, 3), (2, 1), (3, 1)] >>> sorted(sorted(a, key=itemgetter(1), reverse=true), key=itemgetter(0), reverse=true) [(6, 3), (4, 3), (3, 1), (2, 1)] >>> sorted(a, reverse=true) [(6, 3), (4, 3), (3, 1), (2, 1)]
if input has tuples more 2 elements elements must ignored, can still use itemgetter()
, because supports multiple indices (at point returns tuple of values @ indices):
>>> itemgetter(0, 1)(a[0]) (4, 3) >>> sorted(a, key=itemgetter(0, 1), reverse=true) [(6, 3), (4, 3), (3, 1), (2, 1)]
Comments
Post a Comment