Python 以一种棘手的方式连接列表元素

标签 python python-2.7 python-3.x

所以,我有这个列表

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/

相关文章:

python - 在二叉搜索树中找到父级?

python - 如何让字典值枚举的行为类似于Python中的字典键枚举?

python-3.x - webdriver.FirefoxProfile() : Is it possible to use a profile without making a copy of it?

python - 使用 xlsxwriter 写入单元格时是否可以应用多种单元格格式?

python - 我如何在 python 中构建这个 block 矩阵?

python - discord.py [mp3 @ 000001dc99bec540] 从比特率估计持续时间,这可能不准确

python - 覆盖 `from my_module import ...`

python - 列表迭代列表如何在 python 中工作?

python - Python Wheels 的条件依赖

python - 为什么变量 = 对象不像变量 = 数字那样工作