【问题标题】:Append _ to the beginning of items in a list that start with multiple '('将 _ 附加到列表中以多个 '(' 开头的项目的开头
【发布时间】:2017-05-31 22:09:20
【问题描述】:

我有一个list

lst = ['(234A2) or (47) and 86', '(((56 or 2B2E1) and 623) and not 876) or 111']

我试图在每个项目前面添加一个_,同时保留() 结构

['(_234A2) or (_47) and _86', '(((_56 or _2B2E1) and _623) and not _876) or _111']

我试过了

lst_split = []

for item in lst:
    lst_split = item.split()

append_lst = []
for item in lst_split:
    if item[0].isdigit():
        item = '_' + item
        append_lst.append(item)
append_lst

['_2B2E1)', '_623)', '_876)', '_111']

如何将_ 添加到以任意数量的( 开头的项目中,以及使用列表理解实现此目的的更简洁的方法是什么?

【问题讨论】:

    标签: list python-3.x list-comprehension


    【解决方案1】:

    这似乎是一个使用正则表达式的好地方:

    import re
    
    def prefix_numbers(lst):
        return [re.sub('\d+', lambda match: '_' + match.group(), item) for item in lst]
    

    样本输出:

    >>> lst = ['(234) or (47) and 86', '(((56 or 22) and 623) and not 876) or 111']
    >>> prefix_numbers(lst)
    ['(_234) or (_47) and _86', '(((_56 or _22) and _623) and not _876) or _111']
    

    【讨论】:

    • 这完全符合我的要求,谢谢!应用此方法后,我意识到我的某些术语中包含字母字符(即123A423),这种方法产生了_123A_423。我将如何忽略字母字符并仅附加到开头_123A423?第一个字符总是是一个数值。抱歉,我没有具体说明,有超过 200 万个术语,我没有听懂。
    • \d+ 模式匹配数字序列,如果您的术语更复杂,您可以使用不同的模式。也许\d\w* 或其他东西会匹配您的实际值(匹配一个数字后跟任何“单词”字符,即字母和数字,加上下划线)。您可以使用更具体的字符类:例如,\d[A-Z0-9] 只允许使用数字和大写字母。
    猜你喜欢
    • 2015-02-04
    • 2014-12-29
    • 2010-10-23
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2013-07-28
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多