I am confused on how lists inside lists get sorted.
L = [[1,1,1],[0,9,0],[2,1,1]]
sorted(L)
returns [[0, 9, 0], [1, 1, 1], [2, 1, 1]]
This means that it is not based off sum as 0+9+0 is larger than both of the other ones.
I am confused on how lists inside lists get sorted.
L = [[1,1,1],[0,9,0],[2,1,1]]
sorted(L)
returns [[0, 9, 0], [1, 1, 1], [2, 1, 1]]
This means that it is not based off sum as 0+9+0 is larger than both of the other ones.
No it is based on all the elements of the iterator starting from the first element of the iterator
sorted(L,key=lambda x:(x[0],x[1],x[2]) #==sorted(L)
In case you need by sum
sorted(L,key=sum)
A more simplified version of above code to understand the key argument further
print(sorted(L,key=lambda x: x[0]+x[1]+x[2]))
Built-in sorted
considers each element of an iterable in turn. So, for example, [0, 9, 0]
appears first because 0 < 1
and 0 < 2
.
To help gain intuition, you can test a few examples:
[0,9,0] < [1,1,1] # True
[0,9,0] < [0,8,0] # False
[1,1,1] < [2,1,1] # True
So sorted
works consistently with how comparison operators are defined. Sequence objects in Python usually support lexicographic comparison. To sort by the sum of each list, you need to feed a function to the key
argument, in this case built-in sum
:
res = sorted(L, key=sum)