使用可变数量的参数对列表(使用lambda)进行排序

Pas*_*ten 1 sorting lambda python-2.x

鉴于:

a = [[1,2,3], [1,2], [1,1,1,1]]
Run Code Online (Sandbox Code Playgroud)

如何a根据值的总和进行排序?

我尝试使用lambda,但是它因lambda错误而不允许可变数量的参数:

a.sort(lambda x: sum(x))
TypeError: <lambda>() takes exactly 1 arguments (2 given)
Run Code Online (Sandbox Code Playgroud)

前面是一个简化的例子; 我实际上尝试使用另一个带有多个参数的函数...这确实改变了问题.

a.sort(lambda x: len(my_function("123", x)))
Run Code Online (Sandbox Code Playgroud)

希望答案可以在基础python中完成.

Ale*_*ton 5

a.sort(key=sum)  # Need the 'key' keyword, and don't bother with lambda here.
Run Code Online (Sandbox Code Playgroud)

是你想要的.

输出:

[[1, 2], [1, 1, 1, 1], [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

编辑:

要修复多参数示例,只需再次指定key参数:

a.sort(key=lambda arg1, arg2, etc: function(arg1, arg2, etc))
Run Code Online (Sandbox Code Playgroud)


ssh*_*124 5

你可以这样做:

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]]
Run Code Online (Sandbox Code Playgroud)