list.sort with lambda acception 2 parameters
Question:
I am upgrading to python 3.5.2 from python 2.6, And i have changed to python 3.5.2 and fixed almost all of the changes. now i am facing an issue while sorting a list.
My previous code is as follows :
somelist_variable = [{"idx" : 9, "name": "Syed"}, {"idx": 2, "name": "Mex"}]
somelist_variable.sort(lambda a, b: int(a.get("idx")) - int(b.get("idx")))
this above code works fine in python 2.6 , however it is giving an error python 3.5.2, i have checked alot of places to pass 2 parameters to the lambda but i couldnt find anything. Can anyone of you guys help me out with it.
Thanks.
Answers:
This should works in your case
somelist_variable = sorted(somelist_variable, key = lambda x: x.get("idx"))
Okay, can U explain what u want? If U just want to sort somelist_variable by “idx” keyword argument u should write:
somelist_variable.sort(key=lambda a: int(a.get("idx")))
or advanced
from operator import itemgetter
somelist_variable.sort(key=itemgetter('idx'))
The function should only take one argument. The smaller the return value, the earlier in the list the element will be placed:
somelist_variable.sort(key=lambda a: int(a.get("idx")))
Also, you have to explicitly specify that the argument to list.sort
is a key.
I am upgrading to python 3.5.2 from python 2.6, And i have changed to python 3.5.2 and fixed almost all of the changes. now i am facing an issue while sorting a list.
My previous code is as follows :
somelist_variable = [{"idx" : 9, "name": "Syed"}, {"idx": 2, "name": "Mex"}]
somelist_variable.sort(lambda a, b: int(a.get("idx")) - int(b.get("idx")))
this above code works fine in python 2.6 , however it is giving an error python 3.5.2, i have checked alot of places to pass 2 parameters to the lambda but i couldnt find anything. Can anyone of you guys help me out with it.
Thanks.
This should works in your case
somelist_variable = sorted(somelist_variable, key = lambda x: x.get("idx"))
Okay, can U explain what u want? If U just want to sort somelist_variable by “idx” keyword argument u should write:
somelist_variable.sort(key=lambda a: int(a.get("idx")))
or advanced
from operator import itemgetter
somelist_variable.sort(key=itemgetter('idx'))
The function should only take one argument. The smaller the return value, the earlier in the list the element will be placed:
somelist_variable.sort(key=lambda a: int(a.get("idx")))
Also, you have to explicitly specify that the argument to list.sort
is a key.