【问题标题】:How to re.search() multiple patterns in python?如何在 python 中 re.search() 多个模式?
【发布时间】:2018-01-16 05:54:32
【问题描述】:

我有一个这样的列表:

['t__f326ea56',
 'foo\tbar\tquax',
 'some\ts\tstring']

我想得到这样的 4 个不同变量的结果:

s1 = 't__f326ea56'
s2 = ['foo', 'some']
s3 = ['bar', 's']
s4 = ['quax', 'string']

通常我可以搜索re.search(r'(.*)\t(.*)\t(.*)', lst).group(i) 来获取 s2、s3、s4。但是我不能同时搜索所有 4 个。re 模块中有什么特殊的选项可以使用吗?

谢谢

【问题讨论】:

    标签: python regex string list


    【解决方案1】:

    您可以在re 模块中使用split() 方法:

    import re
    
    s = ['t__f326ea56',
    'foo\tbar\tquax',
    'some\ts\tstring']
    
    new_data = [re.split("\\t", i) for i in s]
    s1 = new_data[0][0]
    
    s2, s3, s4 = map(list, zip(*new_data[1:]))
    

    输出:

    s1 = 't__f326ea56'
    s2 = ['foo', 'some']
    s3 = ['bar', 's']
    s4 = ['quax', 'string']
    

    编辑:

    对于列表列表:

    s = [['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring'], ['second\tbar\tfoo', 'third\tpractice\tbar']]
    
    new_s = [[re.split("\\t", b) for b in i] for i in s]
    

    new_s现在商店:

    [[['t__f326ea56'], ['foo', 'bar', 'quax'], ['some', 's', 'string']], [['second', 'bar', 'foo'], ['third', 'practice', 'bar']]]
    

    转置new_s中的数据:

    new_s = [[b for b in i if len(b) > 1] for i in new_s]
    
    final_s = list(map(lambda x: zip(*x), new_s))
    

    final_s 现在将以您想要的原始方式存储数据:

    [[('foo', 'some'), ('bar', 's'), ('quax', 'string')], [('second', 'third'), ('bar', 'practice'), ('foo', 'bar')]]
    

    【讨论】:

    • 谢谢我收到这个错误,ValueError: too many values to unpack (expected 3),当我在列表中运行它时。有什么想法吗?
    • 有道理。谢谢!
    • 很高兴能帮上忙!
    【解决方案2】:

    使用“直”str.split()函数:

    l = ['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring']
    items1, items2 = l[1].split('\t'), l[2].split('\t')
    s1, s2, s3, s4 = l[0], [items1[0], items2[0]], [items1[1], items2[1]], [items1[2], items2[2]]
    print(s1, s2, s3, s4)
    

    输出:

    t__f326ea56 ['foo', 'some'] ['bar', 's'] ['quax', 'string']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2015-08-02
      相关资源
      最近更新 更多