簡體   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