所以,我有这个列表
l = ['abc', 'retro', '', '', 'images', 'cool', '', 'end']
并且,我想以如下方式加入他们:
l = ['abc retro', '', '', 'images cool', '', 'end']
我尝试了很多方法,但似乎没有任何效果。有什么建议吗?
最佳答案
您可以使用 itertools.groupby
和列表理解。分组为 ''
和非 ''
并使用 str.join
连接来自后者的项目.推导式后面的三元运算符使用组键来决定对每个组做什么:
from itertools import groupby
l = ['abc','retro','','','images','cool','','end']
r = [j for k, g in groupby(l, lambda x: x=='')
for j in (g if k else (' '.join(g),))]
print(r)
# ['abc retro', '', '', 'images cool', '', 'end']
关于Python 以一种棘手的方式连接列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43252442/