>> L = [[9, 1], [3, 4]]
>> sorted(L, key=lambda x:x[0])
[[3,4], [9,1]]
The above will sort the list according to the first element, meaning that the list with the smallest first element will appear first.
However, what does the following mean?
>> L = [[9, 1], [3, 4]]
>> sorted(L, key=lambda x:(x[0], x[1]))
[[3,4], [9,1]]
Or even
>> L = [[9, 1], [3, 4]]
>> sorted(L, key=lambda x:(x[0], x[1], x[0]))
[[3,4], [9,1]]
I'm not sure what keys mean when they have more than one item.
Hope this makes it clear:
>>> L
[[9, 1], [3, 4], [3, 2], [9, 0]]
>>> sorted(L, key=lambda x:(x[0], x[1]))
[[3, 2], [3, 4], [9, 0], [9, 1]]
Sort by first and then second element of the sublist.
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.