【发布时间】:2019-12-31 00:30:46
【问题描述】:
我正在使用 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.']
元素 '"somewhere' 在开头保留其引号。我单独运行了正则表达式,它似乎工作正常,但是当我应用过滤器时,事情就崩溃了。哪里出了问题?
【问题讨论】:
-
你读过
filter函数的签名吗? -
值得一提的是,这是python中的列表,不是数组。这对答案并不重要,但在尝试搜索解决方案时会产生很大的不同
标签: python arrays python-3.x filter