我有一个简单的程序,它应该按键对数组进行排序。
为什么sorted()
函数说它只需要一个参数,而我没有提供任何参数?
import operator
array = [[1, 6, 3], [4, 5, 6]]
sorted_array = sorted(iterable=array, key=operator.itemgetter(array[0][1]), reverse=True)
print(sorted_array)
这给出的错误是:
Traceback (most recent call last):
File "...", line 4, in <module>
sorted_array = sorted(iterable=array, key=operator.itemgetter(array[0][1]), reverse=True)
TypeError: sorted expected 1 argument, got 0
您的困惑是合理的。错误:
TypeError: sorted expected 1 argument, got 0
一开始就有点令人困惑。它的实际含义是:
排序了预期的1[position]参数,得到了0
查看文档,签名为:
sorted(iterable, *, key=None, reverse=False)
据此,函数签名中的空*
意味着以下所有参数都必须命名为。这并没有说明前面的论点。
当在交互式外壳中打印help(sorted)
时,会给出更准确的签名:
sorted(iterable, /, *, key=None, reverse=False)
根据这一点,函数签名中的/
意味着所有前面的参数都必须是位置,即未命名,这就解释了错误。您只需要将数组作为位置参数传递:
sorted_array = sorted(array, key=..., reverse=True)
关于itemgetter
作为密钥的正确使用,请参阅@Rivers的回答。
我已经在官方Python错误跟踪器上报告了这个文档问题。
我会给你一个清晰详细的解释:
有两个问题:
iterable
不是命名参数itemgetter
语法错误
1-可重复性:
这是sorted
函数的定义(请参阅https://docs.python.org/3/library/functions.html#sorted):sorted(iterable, *, key=None, reverse=False)
也许您认为iterable
是一个命名参数,但事实并非如此。命名参数为key
和reverse
(它们的名称后面有等号(=((。
所以你不必写iterable=something
。您只需要给出一个可迭代的数据结构,所以在您的示例中,这就是名为array
:的变量
sorted_array = sorted(array,...)
更新:请参阅@Tomerikoo的回答,了解在这种情况下为什么不起作用
2-Itemgetter:你不能写itemgetter(array[0][1])
,你只需要给出元素的索引,所以正如@Ajay在他的评论中所写的那样,你可以写这个:
itemgetter(0,1)
但是,如果您真的想按array[0][1]
排序,那么也应该使用@Ajay所写的lambda函数。
一体化:
from operator import itemgetter
array = [[1,6,3], [4,5,6]]
sorted_array = sorted(array, key=itemgetter(0,1), reverse=True)
print(sorted_array)
输出:
[[4, 5, 6], [1, 6, 3]]