Dav*_*ave -1 python arrays filter python-3.x
我正在使用Python 3.7。我想将正则表达式应用于列表中的每个元素。这是清单
>>> title_words
['that', 'the', 'famous', 'ukulele', 'medley', '"somewhere', 'over', 'the', 'rainbow/what', 'a', 'wonderful', 'world"', 'by', 'israel', 'kamakawiwoê»ole', 'was', 'originally', 'recorded', 'in', 'a', 'completely', 'unplanned', 'session', 'at', '3:00', 'in', 'the', 'morning,', 'and', 'done', 'in', 'just', 'one', 'take.']
Run Code Online (Sandbox Code Playgroud)
我以为对列表运行过滤器可以解决问题,但请注意,当我运行时
>>> list(filter(lambda s: re.sub(r'^\W+|\W+$', '', s), title_words))
['that', 'the', 'famous', 'ukulele', 'medley', '"somewhere', 'over', 'the', 'rainbow/what', 'a', 'wonderful', 'world"', 'by', 'israel', 'kamakawiwoê»ole', 'was', 'originally', 'recorded', 'in', 'a', 'completely', 'unplanned', 'session', 'at', '3:00', 'in', 'the', 'morning,', 'and', 'done', 'in', 'just', 'one', 'take.']
Run Code Online (Sandbox Code Playgroud)
元素““某处”在开头保留了它的引号。我单独运行了正则表达式,它似乎可以正常工作,但在应用过滤器时出现了故障。哪里出了问题?
filter检查过滤器功能的结果是否“真实”以将其包括在结果中。它不会更改元素的值。在这里,您要调用的方法re.sub每次都返回一个非空字符串。
因此,您的原始列表不变。您的意思是简单的列表理解:
filtered = [re.sub(r'^\W+|\W+$', '', s) for s in title_words]
Run Code Online (Sandbox Code Playgroud)
同样,即使需要过滤时,filter它也不是很有用lambda,当带有条件的列表/生成器理解可以做同样的事情时,它会使事情变得更加复杂,而且更加清楚。现在,我意识到您可能想要map代替(也list()可以强制迭代并获得一个硬列表),该方法本可以起作用,但仍然过于复杂:
list(map(lambda s: re.sub(r'^\W+|\W+$', '', s), title_words))
Run Code Online (Sandbox Code Playgroud)
(此方法的唯一兴趣是当您使用multiprocessing.map模块并行化任务时,但此处不适用)