为什么sorted()函数说传递3个参数时只需要一个参数?
我有一个简单的程序,它应该按键对数组进行排序。
为什么sorted()函数说它只需要 1 个参数,而我没有提供任何参数?
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)
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)
这给出了错误:
回答
你的困惑是有道理的。错误:
TypeError: sorted expected 1 argument, got 0
开始有点混乱。它的实际意思是:
排序预期 1 [位置]参数,得到 0
查看文档,签名是:
sorted expected 1 [positional] argument, got 0
根据this,*函数签名中的裸表示必须命名以下所有参数。这并没有说明前面的论点。
help(sorted)在交互式 shell 中打印时提供更准确的签名:
sorted(iterable, *, key=None, reverse=False)
根据这个,一个/在一个函数的签名意味着所有前面的参数必须是位置,即不叫,现在解释了错误。您只需要将数组作为位置参数传递:
sorted_array = sorted(array, key=..., reverse=True)
请参阅@Rivers 的答案以正确使用itemgetter作为密钥。
我已在官方 Python 错误跟踪器上报告了此文档问题。