我有一个类似于这个lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']的字符串列表,如果它们有或作为分隔符,我想将列表中的单词分开,这样最终的结果就是['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']。我怎样才能做到这一点?我的努力是:
to_ret = []
for words in lst:
splitted = words.split(' and')
to_ret.extend(splitted)
new_ret = []
for words in to_ret:
splitted = words.split(' with')
new_ret.extend(splitted)但这看起来很重复。对清洁代码有什么建议吗?
发布于 2022-01-11 20:02:52
您可以使用正则表达式来处理多个分隔符,并使用链表将所有子列表放在一起。
import re
from itertools import chain
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
output = [w.strip() for w in chain.from_iterable([re.split(r'and|with',x) for x in lst])]
print(output)输出
['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']发布于 2022-01-11 20:03:50
#my interpretation would be
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
toSplitWith= ["and" , "with"]
ans=[]
for word in lst:
for sprt in toSplitWith:
if sprt in word:
ans.extend(word.split(sprt))
print(ans)发布于 2022-01-11 20:06:53
如果你喜欢,你可以这样做:-
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
to_ret = []
for i,word in enumerate(lst):
splittedand = word.split(' and')
splittedwith = word.split(' with')
to_ret.extend(splittedand)
to_ret.extend(splittedwith)
to_ret.remove(word)
print(to_ret)退出:
['John Kim', ' Kerry Lin', 'John Cena', 'Kim Rai', ' Kaster Baldwin']https://stackoverflow.com/questions/70672708
复制相似问题