繁体   English   中英

迭代拆分列表元素

[英]split list elements iteratively

我想拆分一个列表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'Oscar\sMuller\s', i))) for i in names]

也没有做任何事情。

d1 = re.compile(r"Oscar\sMuller\s")
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"Oscar\sMuller\s")
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 个项目子列表,然后将列表展平为单个可迭代对象。

有几种方法可以做到这一点。 您可以使用生成器 function,或者巧妙地使用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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM