什么是key = lambda [英] What is key=lambda

查看:1788
本文介绍了什么是key = lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然使用一些内置函数,例如排序,求和... 我注意到key=lambda

While using some built-in functions like sorted, sum... I noticed the usage of key=lambda

什么是lambda?它是如何工作的?

What is lambda? How does it work?

还有哪些其他功能使用key = lambda?

What other functions use key=lambda?

是否还有其他键值,例如key=?

Are there any other key values like, key=?

推荐答案

A lambda 是匿名函数:

A lambda is an anonymous function:

>>> f = lambda: 'foo'
>>> print f()
foo

它经常用在诸如sorted()之类的以可调用函数作为参数(通常是key关键字参数)的函数中.只要它是可调用的对象,就可以在其中提供一个现有函数,而不是lambda.

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.

sorted()函数为例.它将以排序的顺序返回给定的iterable:

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']

但是将大写单词排在小写单词之前.使用key关键字,您可以更改每个条目,以便对它们进行不同的排序.我们可以在排序之前将所有单词都小写,例如:

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']

我们必须为此创建一个单独的函数,我们无法将def lowercased()行内联到sorted()表达式中:

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

另一方面,可以直接在sorted()表达式中内联指定

A lambda:

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']

Lambda仅限于一个表达式,其结果是返回值.

Lambdas are limited to one expression only, the result of which is the return value.

Python库中有很多地方,包括内置函数,这些地方都带有可调用的关键字或位置参数.这里要说的太多了,它们通常扮演着不同的角色.

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屋!

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