首页 > 解决方案 > 连接列表直到某个字符

问题描述

我有这个清单:

Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

我想将列表连接如下:

Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']

这有可能吗?

谢谢,

标签: pythonpython-3.xlistconcatenation

解决方案


这是一个示例解决方案:

jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

groups = [[]]
for part in jokes:
    if part:
        groups[-1].append(part)
    else:
        groups.append([])

result = [' \n '.join(joke) for joke in groups]
print(result)

推荐阅读