划分列表元素迭代
我想拆分列表名称
元素。更重要的是,我只想用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),i))))in name]
也没有做任何事情。
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:必须是str或none,而不是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:必须是str或none,不列表
问题:我在做什么错?
I want to split a list names
element. More precicely i only want to split the strings with 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]
That didnt do anything.
[list(filter(None, re.split(r'Oscar\sMuller\s', i))) for i in names]
didnt do anything either.
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]
but it caused issues with input .split()
. Error: TypeError: must be str or None, not re.Pattern
. So i changed it to process each list element.
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]
But it didnt work either, returning TypeError: must be str or None, not list
Question: What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以使用列表理解使其成为一行:
You can also use list comprehension to make it one line:
从本质上讲,您需要做的是为原始列表中的每个项目生成1或2个项目的订书机,然后将列表变成单个迭代。
您可以做几种方法。您可以使用生成器函数,也可以巧妙地使用
itertools
,也可以使用
itertools
:Essentially, what you need to do is generate 1 or 2 item sublists for each item in the original list, and then flatten the list into a single iterable.
A couple ways you could do this. You could use a generator function, or some clever use of
itertools
Or you could one-liner it with
itertools
: