国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

What is key=lambda in python

2019-11-06 08:52:16
字體:
供稿:網(wǎng)友

原文地址: http://stackoverflow.com/questions/13669252/what-is-key-lambda

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 “”, 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.


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 韶关市| 阿克陶县| 彰化县| 崇左市| 讷河市| 隆安县| 十堰市| 枝江市| 海阳市| 张家港市| 东台市| 嘉善县| 吴旗县| 松滋市| 永善县| 吴桥县| 珠海市| 湖南省| 镇平县| 德清县| 施甸县| 德兴市| 密山市| 宁陕县| 静安区| 麻江县| 阳原县| 成都市| 滦平县| 藁城市| 顺义区| 灵武市| 泾阳县| 宣武区| 襄樊市| 广安市| 武功县| 克什克腾旗| 辽宁省| 荆州市| 咸丰县|