繁体   English   中英

为什么我的过滤器对我的Python列表不起作用?

[英]Why isn't my filter working against my Python list?

我正在使用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.']

我以为对列表运行过滤器可以解决问题,但请注意,当我运行时

>>> 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.']

元素““某处”在开头保留了它的引号。我单独运行了正则表达式,它似乎可以正常工作,但在应用过滤器时出现了故障。哪里出了问题?

filter检查filter函数的结果是否“真实”以将其包括在结果中。 它不会更改元素的值。 在这里,您要调用re.sub ,每次都会返回一个非空字符串。

因此,您的原始列表不变。 您的意思是简单的列表理解:

filtered = [re.sub(r'^\W+|\W+$', '', s) for s in title_words]

同样,即使需要filter ,对于lambda来说, filter也不是那么有用,当带有条件的列表/生成器理解可以做同样的事情时,它会使事情变得更加复杂,而且更加清楚。 现在,我意识到您可能想要使用map (也可以使用list()来强制迭代并获得一个硬列表),该方法虽然可行,但仍然过于复杂:

list(map(lambda s: re.sub(r'^\W+|\W+$', '', s), title_words))

(此方法的唯一兴趣是当您使用multiprocessing.map模块并行化任务时,但此处不适用)

当您真正想要的是地图时,您正在使用过滤器。 用地图替换过滤器,您应该得到想要的结果。

list(map(lambda s: re.sub(r'^\W+|\W+$', '', s), title_words))

编辑:

正如Jean和Olivier所提到的,如果您只是想将地图转换为列表,则列表理解是可取的。 仅当您有很长的title_words列表并且不想将转换应用于整个列表,而是想遍历每一项时(例如,如果您的逻辑可能会停在特定的位置,则使用map才是合适的) title_word,无需查看后面的所有title_words)。

fixed_title_words = map(lambda s: re.sub(r'^\W+|\W+$', '', s), title_words)

for title in fixed_title_words:
    if title == 'medley':
        # Perform some action
        break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM