You can do it as:
a = [[1,2,3], [1,2], [1,1,1,1]]
a = sorted(a, key=lambda x: sum(x))
>>> print a
[[1,2], [1,1,1,1], [1,2,3]]
سؤال
Given:
a = [[1,2,3], [1,2], [1,1,1,1]]
How to sort a
in place based on the sum of the values?
I tried using a lambda, but then it errors with a lambda not allowing a variable amount of arguments:
a.sort(lambda x: sum(x))
TypeError: <lambda>() takes exactly 1 arguments (2 given)
The previous was a simplified example; I am actually trying to use another function that takes multiple arguments... this does change the problem.
a.sort(lambda x: len(my_function("123", x)))
Hopefully the answer can be done in base python.
المحلول
You can do it as:
a = [[1,2,3], [1,2], [1,1,1,1]]
a = sorted(a, key=lambda x: sum(x))
>>> print a
[[1,2], [1,1,1,1], [1,2,3]]
نصائح أخرى
a.sort(key=sum) # Need the 'key' keyword, and don't bother with lambda here.
is what you want.
Output:
[[1, 2], [1, 1, 1, 1], [1, 2, 3]]
EDIT:
To fix the multiple argument example, just once again specify the key
argument:
a.sort(key=lambda arg1, arg2, etc: function(arg1, arg2, etc))
Try this ,
>>> a = [[1,2,3], [1,2], [1,1,1,1]]
>>> print sorted(a, key=sum)
[[1, 2], [1, 1, 1, 1], [1, 2, 3]]
>>>