【发布时间】:2021-01-17 22:47:23
【问题描述】:
假设我们有列表
L = ['a', '!b', '!c', 'd', 'e', '!f', 'g', 'h']
如果它以! 开头,我们希望将每个元素与前一个元素连接起来。
预期输出:
M = ['a!b!c', 'd', 'e!f', 'g', 'h']
这可行,但将join 列表转换为字符串,然后将字符串重新拆分为列表可能不必要地复杂:
M = ''.join(('' if l.startswith('!') else '\n') + l for l in L).splitlines()[1:]
# ['a!b!c', 'd', 'e!f', 'g', 'h']
有没有更简单的方法可以根据条件 ('!' in l) 连接列表中的元素?
【问题讨论】:
标签: python list concatenation