python - Sorting several Tuples in a List -
this question has answer here:
- how sort (list/tuple) of lists/tuples? 10 answers
how sort list of tuples in python. example, have:
alist = [ ( 'person', 20, 100 ), ( 'cat', 30, 900 ), ( 'dog', 5, 500 ) ] so want sort tuples using third values (100, 900, , 500) get:
alist = [ ( 'cat', 30, 900 ), ( 'dog', 5, 500 ), ( 'person', 20, 100 ) ] when use answer duplicate question same values back:
data = [ ( 'person', 20, 100 ), ( 'cat', 30, 900 ), ( 'dog', 5, 500 ) ] def sorted_by_second(): sorted(data, key=lambda tup: tup[1]) return data sorted_by_second() and get:
[('person', 20, 100), ('cat', 30, 900), ('dog', 5, 500)]
you can use python sorted method, can specify key parameter function takes element in list input , returns value sorted output (such lambda).
example:
sorted_list = sorted(alist, key = lambda x : x[2])
Comments
Post a Comment