【问题标题】:regex sub not working when used with filter与过滤器一起使用时,正则表达式子不起作用
【发布时间】:2019-11-21 08:34:30
【问题描述】:

我有一个包含特殊字符的字符串列表

state_list = [('Andhra Pradesh',), ('Karnataka',)]

这样可以正常工作

for state in state_list:
    print(re.sub(r'\W+'," ",str(state)))

输出

安得拉邦

卡纳塔克邦

当我使用过滤器执行此操作时

list(filter(lambda state: re.sub(r"\W+", " ", str(state)),state_list))

这行不通! 我原封不动地返回列表。

[('Andhra Pradesh',), ('Karnataka',)]

我期待这样的列表 ['Andhra Pradesh','Karnataka']

我希望从字符串列表中删除 (), 等特殊字符

【问题讨论】:

  • 也许你想要maplist(map(lambda state: re.sub(r"\W+", " ", state[0]),state_list))?
  • map没有帮助,列表中每一项的数据类型都是class 'sqlalchemy.util._collections.result'所以需要先转换成str才能使用re
  • 但是你显示了一个元组列表。试试tuple(state)[0]list(map(lambda state: re.sub(r"\W+", " ", str(tuple(state)[0])),state_list))
  • unique_state_list 打印在屏幕上时,unique_state_list = partnerTableSession.query(partnerTable.c.state).distinct().all() 给了我一个类似[('Andhra Pradesh',), ('Karnataka',)] 的列表。列表中每个元素的data typeclass 'sqlalchemy.util._collections.result'
  • 重点是单独获取item。然后将其大小写为str

标签: python regex filter


【解决方案1】:

re.sub() 不执行重叠替换。您需要自己的循环,这就是为什么它在第一种情况下使用 for 循环起作用的原因。

列表理解将是实现这一目标的理想方式:

[state[0] for state in state_list]

输出:

['Andhra Pradesh', 'Karnataka']

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 2016-03-18
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2018-11-10
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多