python - Sorting values in mutiple lists -
so currently, have list of lists called result contain values this, example:
result[1] = [john, 0.32] result[2] = [mikey, 1.90] result[3] = [sarah, 1.31] result[4] = [nancy, 0.49] result[5] = [billy, 0.13] i want however, sort in descending order number held in index space [1]. system return values in order. have use sorted() function , call index value held? not need resort list is necessary, need output values in descending order.
how go doing exactly?
thanks
use key parameter in sorted function.
sorted(result, key = lambda x:x[1], reverse = true) the reverse = true makes sure items sorted in descending order. important thing noted here key parameter.
key = lambda x:x[1] we pass lambda function key parameter, accepts 1 parameter. sorted picks each element result , pass key function. in our case tuples. key function returns second item in tuples. so, second item in tuple used value of tuple itself, while sorting. means when comapre [john, 0.32] , [mikey, 1.90], comparing 0.32 , 1.90 only.
sorted doesn't change actual list, creates new sorted list. but, if want sort list itself, can use list.sort method, this
result.sort(key = lambda x:x[1], reverse = true)
Comments
Post a Comment