[英]Using startswith in lambda expression and filter function with Python
I'm trying to find the words starting with character "s".我试图找到以字符“s”开头的单词。 I have a list of strings (seq) to check.我有一个要检查的字符串列表(seq)。
seq = ['soup','dog','salad','cat','great']
sseq = " ".join(seq)
filtered = lambda x: True if sseq.startswith('s') else False
filtered_list = filter(filtered, seq)
print('Words are:')
for a in filtered_list:
print(a)
The output is: output 是:
Words are:
soup
dog
salad
cat
great
Where I see the entire list.我在哪里看到整个列表。 How can I use lambda and filter() method to return the words starting with "s"?如何使用 lambda 和 filter() 方法返回以“s”开头的单词? Thank you谢谢
Your filter lambda always just checks what your joined word starts with, not the letter you pass in.你的过滤器 lambda 总是只检查你加入的单词的开头,而不是你传入的字母。
filtered = lambda x: x.startswith('s')
Try this.尝试这个。
seq = ['soup','dog','salad','cat','great']
result = list(filter(lambda x: (x[0] == 's'), seq))
print(result)
or或者
seq = ['soup','dog','salad','cat','great']
result = list(filter(lambda x: x.startswith('s'),seq))
print(result)
both output output
['soup', 'salad']
This is another elegant method if you're okay with not using filter
:如果您可以不使用filter
,这是另一种优雅的方法:
filtered_list = [x for x in seq if x.startswith('s')]
print('Words are: '+ " , ".join(filtered_list))
Output: Output:
Words are: soup , salad
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.