Python TypeError:sort() 不接受位置参数 [英] Python TypeError: sort() takes no positional arguments

查看:36
本文介绍了Python TypeError:sort() 不接受位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to write a small class and want to sort the items based on the weight. The code is provided,

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()不带位置参数的错误堆栈.这里有什么问题?

When I run the program, I get the error stack of Python TypeError: sort() takes no positional arguments. Whats the issue here?

推荐答案

正如它所说的:sort 不接受任何位置参数.它需要一个名为 key 的仅关键字参数:

Exactly what it says: sort doesn't take any positional arguments. It takes a keyword-only argument named key:

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

来自文档:

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

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() 接受两个参数,只能通过关键字传递(仅关键字参数):

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

key 指定一个参数的函数,用于从每个列表元素中提取比较键(例如,key=str.lower).列表中每一项对应的key被计算一次,然后用于整个排序过程.None 的默认值表示直接对列表项进行排序,无需计算单独的键值.

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.

[...]

签名中的*是位置参数和keyword-only参数之间的分隔符;其作为初始参数"的位置表示缺少位置参数.

The * in the signature is the separator between positional parameters and keyword-only parameters; its position as the initial "argument" indicates the lack of positional parameters.

这篇关于Python TypeError:sort() 不接受位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆