簡體   English   中英

lambda 表達式和過濾器 function 從列表中提取單詞

[英]lambda expression and filter function to extract words from a list

我正在編寫一個程序,它使用 lambda 表達式和過濾器 function 提取從“b”開始的所有列表元素,但我只是變得空 []'。

在 []:

x = ['bread','rice','butter','beans','pizza','lasagna','eggs']

criteria = lambda value:value==['b']  
     
c_list = list(filter(criteria,x))
c_list

出去[]:

 []

您可以一起使用filterlambda

list(filter(lambda item: item.startswith('b'), x))

解釋

lambda function will either return True or False based on whether string item startwsith b and filter will just call the same lambda function for each item in the list, and will keep only the records for which lambda returns True value, Finally, you need to type將其轉換為列表,因為過濾器 function 給出了過濾器 object ,它是一個iterable的 .

OUTPUT

['bread', 'butter', 'beans']

您可以只更新您的 lambda 表達式來檢查 value 參數中的第一個字符:要么: criteria = lambda value:value[0]==['b']要么: criteria = lambda value:value.startswith('b')

使用索引檢查單詞的第一個值。

x = ['bread','rice','butter','beans','pizza','lasagna','eggs']

criteria = lambda value:value[0]=='b'
     
c_list = list(filter(criteria,x))

print(c_list)

印刷

['bread', 'butter', 'beans']

我們也可以在這里嘗試使用列表推導:

inp = ['bread','rice','butter','beans','pizza','lasagna','eggs']
output = [x for x in inp if x.startswith('b')]
print(output)  # ['bread', 'butter', 'beans']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM