This post is not the same as How do I sort a list of dictionaries by values of the dictionary in Python?, which I think can not be solved using lambda sort, since the sort should be done on two properties, one ascending and the other descending.
I think it's answer should be
descending on column 2 and ascending on column 3
[1, 5, 7]
[2, 3, 4]
[3, 2, 2]
[1, 2, 3]
[4, 2, 9]
[3, 1, 9]
but the output is:
[1, 5, 7]
[2, 3, 4]
[1, 2, 3]
**[3, 2, 2]** i think it's wrong here
[4, 2, 9]
[3, 1, 9]
The code is as follows
l=[
[1,2,3],
[2,3,4],
[1,5,7],
[3,1,9],
[3,2,2],
[4,2,9]
]
def printlist(l):
for ll in l:
print ll
def comp1(a,b):
if a[1]<b[1]:
return 1
if a[1]==b[1]:
return a[2]>b[2]
else:
return -1
l3=sorted(l,cmp=comp1)
printlist(l3)
So why the program output the wrong answer?
Edit1:
Here I choose cmp
rather than key=itemgetter(2,3)
since there could be more complex structures, which can not be sorted using itemgetter
, but can only be sorted using the cmp
function.