Python TypeError:sort()不接受位置参数

2024-04-24 17:05:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试编写一个小类,并希望根据权重对项目进行排序。提供了代码

class Bird:

    def __init__(self, weight):
        # __weight for the private variable
        self.__weight = weight

    def weight(self):
        return self.__weight

    def __repr__(self):
        return "Bird, weight = " + str(self.__weight)


if __name__ == '__main__':

    # Create a list of Bird objects.
    birds = []
    birds.append(Bird(10))
    birds.append(Bird(5))
    birds.append(Bird(200))

    # Sort the birds by their weights.
    birds.sort(lambda b: b.weight())

    # Display sorted birds.
    for b in birds:
        print(b)

当我运行程序时,我得到Python TypeError: sort() takes no positional arguments的错误堆栈。有什么问题吗?在


Tags: the项目代码selfforreturn排序def
3条回答

查看^{}的文档,我们可以看到key是一个仅限关键字的参数。所以改变路线

birds.sort(lambda b: b.weight())

birds.sort(key=(lambda b: b.weight()))

确切地说:sort不接受任何位置参数。它接受名为key的纯关键字参数:

birds.sort(key=lambda b: b.weight())

documentation

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

[...]

签名中的*是位置参数和关键字参数之间的分隔符;它作为初始“参数”的位置表示缺少位置参数。在

sort()接受一个key参数,而没有其他参数(好吧,它可以接受一个reverse参数)。您为sort()提供了它无法接受的参数。只需在您的lambda之前添加一个key=

错误消息是因为key采用关键字参数,而不是位置参数。位置参数是后面不跟等号和默认值的名称。在

相关问题 更多 >