Any idea how to sort a list that contains elements of type set ? This is the code I'm using:
sorted_by_second = sorted(result_list, key=lambda set: set[1])
Example of how my result_list looks like:
[['past due', '32.86691794423967'], ['code', '23.24240338748313'], ['why:customer','27.65754595407057']]
I would like to sort the list by descending order according to the 2nd element in each tupple of the list elements. The sorted list result should look like
[['past due', '32.86691794423967'], ['why:customer','27.65754595407057'], ['code', '23.24240338748313']]
I suggest to use float
to map the second element from a string to a number. This will allow sorted
to sort by numbers. If you don't use float
, sorted
will sort the second element as strings.
sorted(result_list, key=lambda x: float(x[1]), reverse=True)
Result:
[['past due', '32.86691794423967'],
['why:customer', '27.65754595407057'],
['code', '23.24240338748313']]
Hint: Don't use set
as a name since it is a built-in function .
sortedlst contain the descending sorted elements by second element
lst=[['past due', '32.86691794423967'], ['code', '23.24240338748313'], ['why:customer','27.436']]
sortedlst=sorted(lst,key=lambda x: x[1],reverse=True)
print sortedlst
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.