sorted()我正在通过以下小示例研究Python 3.9 中的函数
circus = [('a', 'b', 'c', 'd', 'e'),('w', 'x', 'y', 'z', 'a'),('k', 'l', 'm', 'n', 'o'),('u', 'v', 'w', 'x', 'y'),('q', 'r', 's', 't', 'u'),('e', 'f', 'g', 'h', 'i')]
Run Code Online (Sandbox Code Playgroud)
这只是一个五元组列表,我想按第五个元素(即 e、a、o、y、u、i)排序
我知道正确的方法是
sorted(circus, key = lambda d: d[4], reverse = True)
Run Code Online (Sandbox Code Playgroud)
但我正在尝试这个
sorted(circus, lambda z: z[4], True)
Run Code Online (Sandbox Code Playgroud)
并得到错误
TypeError: sorted expected 1 argument, got 3
Run Code Online (Sandbox Code Playgroud)
我试图理解为什么它需要 1 个参数。根据文档(https://www.w3schools.com/python/ref_func_sorted.asp),另外两个是可选参数,但它们仍然应该是预期的,对吗?
如果您查看sorted( help(sorted))的签名
sorted(iterable, /, *, key=None, reverse=False)\nRun Code Online (Sandbox Code Playgroud)\n您将看到可迭代参数仅是位置参数,而其他两个参数仅是关键字参数。您不能使用关键字参数来iterable=[1,2,3]提供可迭代的排序,并且正如您所看到的,您不能使用位置参数指定键函数或反向标志。
\n\n\xe2\x80\x9c
\n*\xe2\x80\x9d 或 \xe2\x80\x9c*identifier\xe2\x80\x9d 之后的参数是仅关键字参数,只能通过关键字参数传递。\xe2\x80\x9c \xe2\x80\x9d 之前的参数/是仅位置参数,只能通过位置参数传递。
| 归档时间: |
|
| 查看次数: |
856 次 |
| 最近记录: |