Python 为什么sorted()函数在传递3个参数时只接受一个参数?
我有一个简单的程序,它应该按键对数组进行排序 为什么Python 为什么sorted()函数在传递3个参数时只接受一个参数?,python,Python,我有一个简单的程序,它应该按键对数组进行排序 为什么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) 由此产生的误差是: 回溯(最近一次呼叫最后一次): 文件“…”,第4
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)
由此产生的误差是:
回溯(最近一次呼叫最后一次):
文件“…”,第4行,在
sorted_array=sorted(iterable=array,key=operator.itemgetter(数组[0][1]),reverse=True)
TypeError:排序后的参数应为1,得到0
我会尽量给你一个清晰详细的解释:
有两个问题:
iterable
不是命名参数itemgetter
语法错误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]]
这是排序的函数的定义(请参阅):
sorted(iterable,*,key=None,reverse=False)
也许您认为iterable
是一个命名参数,但它不是。命名参数是键
和反向
(它们的名称后面有等号(=)
因此,您不必编写iterable=something
。您只需给出一个iterable数据结构,因此在您的示例中,该变量名为数组
:
sorted_array = sorted(array,...)
更新:请参阅@Tomerikoo答案,以了解在本例中此操作不起作用的确切原因
2-项目获取者:
你不能写itemgetter(数组[0][1])
,你只需要给出元素的索引,就像@Ajay在他的评论中写的那样,你可以这样写:
itemgetter(0,1)
但是,如果您确实想按数组[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]]
输出:
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]]
你的困惑是有道理的。错误:
TypeError:排序后的参数应为1,得到0
一开始有点混乱。它的实际含义是:
sorted expected 1 [positional] argument, got 0
根据,函数签名中的裸*
意味着以下所有参数必须命名为。这并没有说明前面的论点
在交互式shell中打印帮助(已排序)
时,签名更准确:
排序(iterable,/,*,key=None,reverse=False)
根据,函数签名中的/
表示所有前面的参数必须是位置的,即未命名,这就解释了错误。只需将数组作为位置参数传递:
sorted_array = sorted(array, key=..., reverse=True)
有关如何正确使用itemgetter
作为键,请参阅
我已经在上报告了此文档问题。那么它说了什么?一次不能有两条不同的错误消息。请显示准确的错误回溯。@mkrieger1它确实说了两个:TypeError:sorted预期1参数,得到0。听起来不错@Ajay我会调查的lambdas@Ajay为什么?<代码>运算符
模块主要用于用预定义的运算符函数替换lambda的使用。。。i、 e.不使用lambda x,y:x+y
而只使用运算符。添加
…请注意,参数不是通过具有默认值来命名的。使用def foo(a):打印(a)
并将其命名为foo(a=5)
,这是完全正确的。请查看我的答案,了解这不起作用的真正原因。非常感谢您指出这一点,我编辑了我的答案。