Reputation: 13
I have a nested list
a=[[x1,y1],[x2,y2],[x1,y2],[x2,y1],[x7,y7],[x1,y3]]
I want to sort it as:
a=[[x1,y1],[x1,y2],[x1,y3],[x2,y1],[x2,y2],[x7,y7]]
I tried to use lambda function but it wouldn't compile:
a=sorted(a,lambda x,y:x==y?x[0]+x[1],x[0])
How do I use sorted
to get my desired output?
Upvotes: 1
Views: 192
Reputation: 1121476
You could use actual Python syntax, such as a conditional expression:
sorted(a, key=lambda x: x[0] + x[1] if x == y else x[0])
This is based on a interpreting your ?
syntax as the Javascript conditional expression syntax.
This of course assumes there is a separate y
variable defined somewhere:
>>> a = [[1,1], [2,2], [1,2], [2,1], [7,7], [1,3]]
>>> y = [1, 1]
>>> sorted(a, key=lambda x: x[0] + x[1] if x == y else x[0])
[[1, 2], [1, 3], [1, 1], [2, 2], [2, 1], [7, 7]]
Upvotes: 1
Reputation: 47012
I believe sorted(a)
will give what you want, right out-of-the box:
>>> a = [[1,1], [2,2], [1,2], [2,1], [7,7], [1,3]]
>>> sorted(a)
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [7, 7]]
Upvotes: 1