python - 如何在 python 中重新搜索()多个模式?

标签 python regex string list

我有一个这样的列表:

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

关于python - 如何在 python 中重新搜索()多个模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45572091/

相关文章:

python - 如何使用 scapy 获取我自己的本地 IP?

连接到使用 Nodejs 创建的 socket.io 服务器的 Python 脚本

mysql - 返回 MySQL 数据库中最小长度的字符串

c - 为什么代码只打印指向字符串的指针数组中最后一个指针的值?

应返回 9 个字符的随机字符串的 Java 函数

python - 文件名约定匹配的正则表达式

python - 在不知道网页结构的情况下使用 Scrapy 抓取所有文本

Javascript正则表达式重复行匹配无法正常工作

regex - Terraform GCP 正则表达式中不支持的转义序列

javascript - 有没有办法根据浏览器url更改所有页面链接url?