python - Sorting several Tuples in a List -


this question has answer here:

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

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -