Simpler way of sorting list of lists indexed by one list in Python -
i want sort list of 2 lists, elements in 2 lists pairs.
i want sort lists second element in these pairs.
for example if have
a_list = [[51132, 55274, 58132], [190, 140, 180]]
and want
sorted_list = [[55274, 58132, 51132], [140, 180, 190]]
is there simpler way following in python2.7?
from operator import itemgetter sorted_list = map(list, zip(*sorted(map(list,zip(*a_list)), key=itemgetter(1))))
best regards, Øystein
i bit reluctant post answer, why not, actually?
no, there no simpler way achieve sort in python -- except can drop inner map
:
>>> map(list, zip(*sorted(zip(*a_list), key=itemgetter(1)))) [[55274, 58132, 51132], [140, 180, 190]]
it may seem bit convoluted @ first (though not as with additional map
), it's totally clear: zip list, sort second element, , zip back. knows python should understand code does.
if want make clearer, either add line comment describing sort does, or wrap inside function descriptive name , same or more extensive comment.
Comments
Post a Comment