【发布时间】:2020-11-16 09:25:05
【问题描述】:
我想使用 map 函数和 lambda 函数来比较 wordlist 和 checklist 如果单词列表和清单中的单词。这个词将在词表中删除。 任何人都可以帮助我吗?非常感谢
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)
当前结果: 前 ['你好','世界','汤姆'] 后 ['世界','汤姆']
预期结果: 前 ['你好','世界','汤姆'] 后 ['汤姆']
【问题讨论】:
-
在迭代列表时永远不应该从列表中删除项目。
-
@bereal 是对的。最好将所有不匹配的字符串添加到新列表中:
new_lsit = [x for x in wordlist if x not in checklist]
标签: python dictionary if-statement lambda