我想拆分一個串列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
問題:我做錯了什么?
uj5u.com熱心網友回復:
您還可以使用串列推導使其成為一行:
import re
[j for i in [re.split(r"(?<=Oscar Muller)", k) for k in names] for j in i if j]
uj5u.com熱心網友回復:
本質上,您需要做的是為原始串列中的每個專案生成 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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/466043.html
