简体   繁体   English

lambda 表达式和过滤器 function 从列表中提取单词

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

I am writing a program that extracts all list elements starting from 'b' using lambda expression and filter function, but I am just getting empty []'.我正在编写一个程序,它使用 lambda 表达式和过滤器 function 提取从“b”开始的所有列表元素,但我只是变得空 []'。

In []:在 []:

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

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

Out[]:出去[]:

 []

You can use filter and lambda together您可以一起使用filterlambda

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

EXPLANATION :解释

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 cast it to a list, since filter function gives a filter object which is an iterable . 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 : OUTPUT

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

You can just update your lambda expression to check the first character in the value parameter: Either: criteria = lambda value:value[0]==['b'] or: criteria = lambda value:value.startswith('b')您可以只更新您的 lambda 表达式来检查 value 参数中的第一个字符:要么: criteria = lambda value:value[0]==['b']要么: criteria = lambda value:value.startswith('b')

Check the first value of the word using indexing.使用索引检查单词的第一个值。

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

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

print(c_list)

prints印刷

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

We can try using a list comprehension here as well:我们也可以在这里尝试使用列表推导:

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