sorted()如何使用它的关键参数-python

时间:2015-07-06 20:45:09

标签: python lambda

我正在阅读https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions处的lambda表达式,我不明白sort()从何处获取其参数。它显示:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

其中"对:对[1]"在用于lambda之前没有命名。我也做了:

In [23]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

In [24]: pairs.sort(key=lambda x: x[1])

In [25]: pairs
Out[25]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

In [26]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

In [27]: pairs.sort(key=lambda randomname: randomname[1])

In [28]: pairs
Out[28]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

In [29]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

In [30]: pairs.sort(key=lambda randomname: mismatch[1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
...
NameError: global name 'mismatch' is not defined

这告诉我lambda可以接受任何随机参数名称,并且知道从对列表中获取[1]点。

我也不明白" key"甚至采取,正如文档说它需要一个参数的函数,然后使用key=str.lower作为一个例子。但是使用他们的确切示例失败了:

student_tuples
Out[55]: [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ('John', 'b', 5)]


In [60]: sorted(student_tuples, key=str.lower)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-86a57d272cfb> in <module>()
----> 1 sorted(student_tuples, key=str.lower)

TypeError: descriptor 'lower' requires a 'str' object but received a 'tuple'


In [61]: sorted(student_tuples, key=str.lower())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-983b5ca19cdb> in <module>()
----> 1 sorted(student_tuples, key=str.lower())

TypeError: descriptor 'lower' of 'str' object needs an argument

即使将字符串作为可迭代项提供,str.lower方法也会失败:

In [68]: strings
Out[68]: ['str', 'str2', 'str3']

In [69]: sorted(strings, str.lower)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-271d28a2618f> in <module>()
----> 1 sorted(strings, str.lower)

TypeError: lower() takes no arguments (1 given)

我的问题是

  1. 如何知道lambda函数在当前iterable中分配位置(调用iterable本身得到TypeErro:'tuple' object is not callable

  2. 究竟是什么关键,只做lambdas?

  3. 谢谢

0 个答案:

没有答案