Reputation: 339
I want to compare the wordlist and the checklist by using map function and lambda function if the words in wordlist and checklist. this words will be deleted in wordlist. Anyone can help me? thanks a lot
wordlist = ['hello','world','Tom']
checklist = ['hello','world']
print('before')
print(wordlist)
list(map(lambda x: wordlist.remove(x) if x in checklist else None ,wordlist))
print('after')
print(wordlist)
Current Result: before ['hello', 'world', 'Tom'] after ['world', 'Tom']
Expected result: before ['hello', 'world', 'Tom'] after ['Tom']
Upvotes: 1
Views: 1408
Reputation: 42312
map
always produces one output item for each input item, it can not remove elements. Furthermore, map
should not be used to mutate objects, that's not its job, and because it's lazy the results can be unexpected.
filter
is designed to create an output with less elements than the input, although it's mostly useful if you already have a ready-made predicate (filtering) function.
Since you do not, you can and should use comprehensions which provide a relatively terse way to perform iteration, filtering, mapping and collection in a single construct:
wordlist = ['hello','world','Tom']
checklist = ['hello','world']
print('before')
print(wordlist)
wordlist = [word for word in wordlist if word not in checklist]
print('after')
print(wordlist)
ps: if you want to modify things in-place, use a regular loop
Upvotes: 2
Reputation: 24052
The problem is you're removing elements from wordlist
while iterating over it, which interferes with the iteration. But map
is the wrong thing to use for this.
The closest solution to what you're doing now uses filter
:
x = list(filter(lambda x: x not in checklist, wordlist))
This returns a filter object which is then converted to a list.
It's probably better to just use a list comprehension:
y = [x for x in wordlist if x not in checklist]
These both produce the same result.
Note that if checklist
is large, it would be more efficient to create a set first, then check for membership in the set, e.g. checkset = set(checklist)
, then x not in checkset
. Functionally it's the same, but the set is more efficient if checklist
is large.
Upvotes: 1
Reputation: 343
You can try this instead, which doesn't use lambda
but accomplishes your goal. Let us know if you absolutely must use lambda
. The issue with your lambda expression is that your modifying the list that you are providing to map in the lambda function.
wordlist_2 [word for word in wordlist if word not in checklist and word]
The last and word
is to not add None
to your list.
Upvotes: 1