国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 丰都县| 江津市| 平凉市| 新绛县| 潼关县| 鹤峰县| 浦县| 宁远县| 板桥市| 临清市| 泾源县| 定州市| 义马市| 上蔡县| 闸北区| 兰州市| 都匀市| 南京市| 循化| 贵溪市| 澜沧| 柞水县| 盘锦市| 临沧市| 威宁| 曲阜市| 华阴市| 河间市| 泗水县| 封丘县| 武隆县| 浦北县| 南宁市| 武汉市| 浦江县| 台南县| 长垣县| 连城县| 类乌齐县| 应城市| 罗江县|