-3

How do I filter out the letter in the set of words with lambda function?

For example:

I have to filter out every word containing letter "K".

["rabbit", "chuck", "Joe", "war", "rock", "docker"]
["chuck", "rock", "docker"]

I was told to provide the efforts:

list = ["rabbit", "chuck", "Joe", "war", "rock", "docker"]
print(list)
listfilter = list(filter(lambda x: (x == 'k'), lst))
print(listfilter)

2 Answers2

0

Read about Python's filter function. Example:

words = ['rabbit', 'chuck', 'Joe', 'war', 'rock', 'docker']
filtered_out = list(filter(lambda item: 'k' not in item, words))  # filtered out
print(filtered_out)
Dennis
  • 2,271
  • 6
  • 26
  • 42
  • Using the `filter` function was not the problem. The problem was to supply a `lambda` that does the correct thing. – mkrieger1 Feb 26 '22 at 21:32
0

There are two issues with your code:

  1. The list variable name shadows the list() builtin -- pick a different name for your original list instead.
  2. Your lambda function isn't correct. Instead of lambda x: x == k, it should be lambda x: 'k' in x.
data = ["rabbit", "chuck", "Joe", "war", "rock", "docker"]
listfilter = list(filter(lambda x: ('k' in x), data))

# Prints ["chuck", "rock", "docker"]
print(listfilter)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • But the result I "believe" he is trying to achieve is: `["chuck", "rock", "docker"]` not `['rabbit', 'Joe', 'war']` – Seraph Feb 26 '22 at 23:04