迭代地分割列表元素



我想拆分列表names元素。更准确地说,我只想用Oscar Muller

分割字符串。
names = ['Oscar Muller Some other Name', 'Oscar Muller', 'Peter Pan']
expected_names = ['Oscar Muller', 'Some other Name', 'Oscar Muller', 'Peter Pan']

d = "Oscar Muller "
for line in names:
s = [e+d for e in line.split(d) if e]

什么也没做

[list(filter(None, re.split(r'OscarsMullers', i))) for i in names]

也没做任何事。

d1 = re.compile(r"OscarsMullers")
d = d1.search(names)
for line in names:
if d:
s = [e+d for e in line.split(d) if e]

,但它导致输入.split()的问题。错误:TypeError: must be str or None, not re.Pattern。所以我改变它来处理每个列表元素。

d1 = re.compile(r"OscarsMullers")
d = list(filter(d1.match, names))
for line in names:
if d:
s = [e+d for e in line.split(d) if e]

但是它也不工作,返回TypeError: must be str or None, not list

我做错了什么?

您也可以使用列表推导式将其变成一行:

import re
[j for i in [re.split(r"(?<=Oscar Muller)", k) for k in names] for j in i if j]

本质上,您需要做的是为原始列表中的每个项目生成1或2个项目子列表,然后将该列表扁平化为单个可迭代对象。

有几种方法可以做到这一点。您可以使用生成器函数,或者巧妙地使用itertools

import re
def my_generator(names):
for name in names:
sublist = re.split(r"(?<=Oscar Muller) ", name)
yield from sublist
names = ['Oscar Muller Some other Name', 'Oscar Muller', 'Peter Pan']
expected_names = list(my_generator(names))

或者您可以使用itertools:

一行代码
import itertools
import re
names = ['Oscar Muller Some other Name', 'Oscar Muller', 'Peter Pan']
expected_names = list(itertools.chain.from_iterable(re.split(r"(?<=Oscar Muller) ", s) for s in names))

最新更新