【问题标题】:Why isn't my filter working against my Python list?为什么我的过滤器对我的 Python 列表不起作用?
【发布时间】: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


【解决方案1】:

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

所以你的原始列表没有改变。你的意思是一个简单的列表理解:

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

此外,即使需要过滤,filterlambda 也没有那么有用,当带有条件的列表/生成器理解可以做同样的事情并且更清晰时,它只会使事情变得过于复杂。现在我意识到你可能想要map 代替(还有list() 来强制迭代并获得一个硬列表),这本来可以,但仍然过于复杂:

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

(对这种方法唯一感兴趣的是当您使用multiprocessing.map 模块来并行化任务时,但这里不适用)

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2023-03-13
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      相关资源
      最近更新 更多