说我有这样的清单:
myList = ['this\n', 'is\n', 'sparta\n']
如何在不创建新列表的情况下实现以下结果,执行某些逻辑并将其复制到...
newList = ['this', '\n', 'is', '\n', 'sparta', '\n']
答案 0 :(得分:1)
在换行符上只拆分一次时,可以使用str.partition()
生成元素列表,然后跳过所有空结果:
newList = [elem for word in myList for elem in word.partition('\n') if elem]
演示:
>>> myList = ['this\n', 'is\n', 'sparta\n']
>>> [elem for word in myList for elem in word.partition('\n') if elem]
['this', '\n', 'is', '\n', 'sparta', '\n']
>>> myList = ['this\n', 'is', 'sparta\n']
>>> [elem for word in myList for elem in word.partition('\n') if elem]
['this', '\n', 'is', 'sparta', '\n']