【问题标题】:In python, how do i extract a sublist from a list of strings by matching a string pattern in the original list在python中,如何通过匹配原始列表中的字符串模式从字符串列表中提取子列表
【发布时间】:2013-04-24 14:59:12
【问题描述】:

如何使用匹配模式返回字符串列表的子列表。例如我有

myDict=['a', 'b', 'c', 'on_c_clicked', 'on_s_clicked', 's', 't', 'u', 'x', 'y']

我想回来:

myOnDict=['on_c_clicked', 'on_s_clicked']

我认为列表推导会起作用,但我对它的确切语法感到困惑。

【问题讨论】:

    标签: python regex list pattern-matching sublist


    【解决方案1】:
    import re
    myOnDict = [x for x in myDict if re.match(r'on_\w_clicked',x)]
    

    应该这样做......


    当然,对于这个简单的例子,你甚至不需要正则表达式:

    myOnDict = [x for x in myDict if x.startswith('on')]
    

    或:

    myOnDict = [x for x in myDict if x.endswith('clicked')]
    

    甚至:

    myOnDict = [x for x in myDict if len(x) > 1]
    

    最后,作为一些不请自来的建议,您可能需要重新考虑您的变量名称。除了 PEP8 命名约定,这些是 list 对象,而不是 dict 对象。

    【讨论】:

    • 谢谢!这完美地工作。仍然对列表推导有所了解。
    【解决方案2】:

    只是猜测,但是...

    for entry in myDict:
        if re.search("^on", entry):
            myOnDict.append(entry)
    

    【讨论】:

    • @mgilson's 更“pythonic”:)
    • 另外,我相信re.search('^on,...)re.match('on',...) 是一回事。
    猜你喜欢
    • 2023-03-28
    • 2013-06-18
    • 2021-07-02
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多