[英]How to re.search() multiple patterns in python?
我有一個這樣的列表:
['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模塊中的任何特殊選項嗎?
謝謝
您可以在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')]]
使用“直” 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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.