Using startswith in lambda expression and filter function with Python
Question:
I’m trying to find the words starting with character "s". I have a list of strings (seq) to check.
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:
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" ? Thank you
Answers:
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
['soup', 'salad']
Your filter lambda always just checks what your joined word starts with, not the letter you pass in.
filtered = lambda x: x.startswith('s')
This is another elegant method if you’re okay with not using filter
:
filtered_list = [x for x in seq if x.startswith('s')]
print('Words are: '+ " , ".join(filtered_list))
Output:
Words are: soup , salad
I’m trying to find the words starting with character "s". I have a list of strings (seq) to check.
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:
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" ? Thank you
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
['soup', 'salad']
Your filter lambda always just checks what your joined word starts with, not the letter you pass in.
filtered = lambda x: x.startswith('s')
This is another elegant method if you’re okay with not using filter
:
filtered_list = [x for x in seq if x.startswith('s')]
print('Words are: '+ " , ".join(filtered_list))
Output:
Words are: soup , salad