Python 将匹配项追加到新列表并从原始列表中删除匹配项
假设我在一个名为“main”的列表中有一组字符串。我如何迭代“main”,如果我找到了匹配项,那么我将删除“main”中匹配的部分,然后将匹配的文本添加到一个名为“new”的新列表中 蟒蛇Python 将匹配项追加到新列表并从原始列表中删除匹配项,python,Python,假设我在一个名为“main”的列表中有一组字符串。我如何迭代“main”,如果我找到了匹配项,那么我将删除“main”中匹配的部分,然后将匹配的文本添加到一个名为“new”的新列表中 蟒蛇 main = ['text \fc + \fr this is my match1 \fc* text', 'text \fc + \fr this is my match2 \fc* text', 'text', 'text', 'text \fc + \fr this is my match \fc* t
main = ['text \fc + \fr this is my match1 \fc* text', 'text \fc + \fr this is my match2 \fc* text', 'text', 'text', 'text \fc + \fr this is my match \fc* text']
new = []
def rematch(pattern, inp):
matcher = re.compile(pattern)
matches = matcher.match(inp)
if matches:
new.append(matches)
#remove match from "main" somehow?
for x in main:
for m in rematch('\\fc \+ \\fr(.*?)\\fc\*', x):
结果:
main = ['text text', 'text text', 'text', 'text', 'text text']
new = ['this is my match1', 'this is my match2', 'this is my match3']
说明: 注意当您使用
pat.split
时会发生什么:
In [37]: pat.split(main[0])
Out[37]: ['text ', ' this is my match1 ', ' text']
这与您想要的类似,只是您需要main
中的奇数项和new
中的偶数项。我们马上就要开始了
首先,让我们将pat.split
应用于main
中的每个项目:
In [51]: [pat.split(m) for m in main]
Out[51]:
[['text ', ' this is my match1 ', ' text'],
['text ', ' this is my match2 ', ' text'],
['text'],
['text'],
['text ', ' this is my match ', ' text']]
接下来,让我们将奇数项与偶数项分开,并使用''。将
合并为一个字符串:
In [52]: [(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]]
Out[52]:
[('text text', ' this is my match1 '),
('text text', ' this is my match2 '),
('text', ''),
('text', ''),
('text text', ' this is my match ')]
从这里,我们可以使用zip(*…)
将main
与new
分开:
In [53]: main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])
In [54]: main
Out[54]: ('text text', 'text text', 'text', 'text', 'text text')
In [55]: new
Out[55]: (' this is my match1 ', ' this is my match2 ', '', '', ' this is my match ')
有没有一种方法可以进行多种模式匹配?我不懂你的意思。你能详细说明你在寻找什么吗?也许可以举个例子吗?我想出来了,我很欣赏这个复杂而漂亮的解决方案:)
In [53]: main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])
In [54]: main
Out[54]: ('text text', 'text text', 'text', 'text', 'text text')
In [55]: new
Out[55]: (' this is my match1 ', ' this is my match2 ', '', '', ' this is my match ')