如何搜索()python中的多个模式?

2024-05-19 16:35:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个清单:

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

我想得到4个不同变量的结果,如下所示:

^{pr2}$

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

谢谢


Tags: researchs3foogroupsomes4ts
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)

输出:

^{pr2}$

您可以在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:]))

输出:

^{pr2}$

编辑:

对于列表:

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')]]

相关问题 更多 >