什么是key=lambda [英] What is key=lambda
问题描述
虽然使用了一些内置函数,如 sorted、sum...我注意到 key=lambda
什么是拉姆达?它是如何工作的?
还有哪些函数使用 key=lambda?
是否还有其他键值,例如 key=?
A lambda
是一个匿名函数:
它常用于诸如sorted()
之类的将可调用对象作为参数(通常是key
关键字参数)的函数.你也可以在那里提供一个现有的函数而不是 lambda
,只要它是一个可调用的对象.
将 sorted()
函数作为一个例子.它将按排序顺序返回给定的可迭代对象:
但这会在小写单词之前对大写单词进行排序.使用 key
关键字,您可以更改每个条目,以便对其进行不同排序.我们可以在排序前将所有单词小写,例如:
我们必须为此创建一个单独的函数,我们无法将 def lowercased()
行内联到 sorted()
表达式中:
A lambda
另一方面,可以直接指定,内联在 sorted()
表达式中:
>>>sorted(['Some', 'words', 'sort', '不同'], key=lambda word: word.lower())['不同','一些','排序','单词']
Lambda 仅限于一个表达式,其结果是返回值.
Python 库中有很多地方,包括内置函数,将可调用对象作为关键字或位置参数.这里有太多无法一一列举了,它们往往扮演着不同的角色.
While using some built-in functions like sorted, sum...
I noticed the usage of key=lambda
What is lambda? How does it work?
What other functions use key=lambda?
Are there any other key values like, key=?
A lambda
is an anonymous function:
>>> f = lambda: 'foo'
>>> print f()
foo
It is often used in functions such as sorted()
that take a callable as a parameter (often the key
keyword parameter). You could provide an existing function instead of a lambda
there too, as long as it is a callable object.
Take the sorted()
function as an example. It'll return the given iterable in sorted order:
>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']
but that sorts uppercased words before words that are lowercased. Using the key
keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:
>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']
We had to create a separate function for that, we could not inline the def lowercased()
line into the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
File "<stdin>", line 1
sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
^
SyntaxError: invalid syntax
A lambda
on the other hand, can be specified directly, inline in the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']
Lambdas are limited to one expression only, the result of which is the return value.
There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.
这篇关于什么是key=lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!