I am using the Python sorted function in order to sort a multidimensional list which has many entries.
Example:
sorted_list = sorted(list_not_sorted, key=lambda x:x[1], reverse=True)
Is there a way to sort it based on the size of the numbers?
Lets say I have the following list:
[
[John,973],
[Jim,99],
[Jason,912345]
]
Using that code will sort it like this:
[
[Jim,99],
[John,973]
[Jason,912345],
]
However I want it sorted like this:
[
[Jason,912345],
[John,973]
[Jim,99],
]
Is there any way to do this with this function?
Question has been edited for clarity!
So close!
sorted_list = sorted(list_not_sorted, key=lambda x:x[1], reverse=True)
x[2]
is out of bounds (as your inner lists only have 2 items, and this is accessing the third). Since you want to key off the number, you want x[1]
.
>>> data = [['John', 973], ['Jim', 99], ['Jason', 912345]]
>>>
>>> sorted(data, key=lambda x:x[1], reverse=True)
[['Jason', 912345], ['John', 973], ['Jim', 99]]
You don't need to create a copy of your data using sorted
. sort
is enough.
>>> l
[['John', 973], ['Jim', 99], ['Jason', 912345]]
>>> l.sort(key=lambda x:x[1], reverse=True)
>>> l
[['Jason', 912345], ['John', 973], ['Jim', 99]]
If you need lexicographic order:
>>> l.sort(key=lambda x:str(x[1]), reverse=True)
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.