Python 缺少 1 个必需的位置参数 - 为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20642332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:54:56  来源:igfitidea点击:

Missing 1 required positional argument - Why?

python

提问by hteo

I have written this code:

我写了这段代码:

keyList=['a','c','b','y','z','x']
letterlist=['b','c','a','z','y','x']

def keyL(x, y):
    xIndex=keyList.index(x)
    yIndex=keyList.index(y)
    print(cmp(xIndex,yIndex))
    return cmp(xIndex,yIndex)



print(letterlist)


letterlist.sort(key=lambda x, y: keyL(x, y))
print(letterlist)

But when I run the code, I have this error:

但是当我运行代码时,我有这个错误:

File "C:\Python33\prova.py", line 14, in <module>
    letterlist.sort(key=lambda x, y: keyL(x, y))
TypeError: <lambda>() missing 1 required positional argument: 'y'

Why? I have written all the arguments of lambda...

为什么?我已经写了 lambda 的所有参数......

采纳答案by Martijn Pieters

The sortkey function is only ever passed oneargument, yet your lambdawants to have 2 arguments. The key function used for list.sort()or sorted()is nota cmp()function.

sort键功能只有一次闯过一个说法,但你lambda想有2个参数。用于关键功能list.sort()sorted()不是一个cmp()函数。

Just use keyList.index()as your key function here:

只需keyList.index()在此处用作您的关键功能:

letterlist.sort(key=keyList.index)

Python then sorts the list based on the values returned by the key function. Under the hood Python will 'decorate' your values with the key function, sort the values, then undecorate again.

Python 然后根据 key 函数返回的值对列表进行排序。在幕后,Python 将使用 key 函数“装饰”您的值,对值进行排序,然后再次取消装饰。

If you do have a complex cmp()function and you don't quite know how to translate it to a key function, you can use the functools.cmp_to_key()utility function to wrap the cmp()function for you:

如果您确实有一个复杂的cmp()函数,并且您不太知道如何将其转换为关键函数,则可以使用functools.cmp_to_key()实用程序cmp()函数为您包装该函数:

from functools import cmp_to_key

letterlist.sort(key=cmp_to_key(keyL))

but do note that the built-in cmp()function has been removed from Python 3 altogether.

但请注意,内置cmp()函数已从 Python 3 中完全删除。