繁体   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