Jos*_*een 6 python merge list python-3.x
我正在尝试将列表项与之前的项合并,如果它们不包含某个前缀,并\n在执行此操作时在所述列表项之间添加.
prefix = '!'
cmds = ['!test','hello','world','!echo','!embed','oh god']
output = ['!test\nhello\nworld','!echo','!embed\noh god']
Run Code Online (Sandbox Code Playgroud)
我试过类似的东西
for i in list(range(0,len(cmds))):
if not cmds[i+1].startswith(prefix):
cmds[i] += cmds.pop(i+1)
Run Code Online (Sandbox Code Playgroud)
但总是得到list index out of range错误.
我很抱歉,如果措辞不好,或者看起来像是一个明显的修复,我对python /编程很新.
编辑:
我设法让它与之合作
prefix = '!'
cmds = ['!test','hello','world','!echo','!embed','oh god']
print(list(range(0,len(cmds))))
for i in reversed(range(len(cmds))):
if not cmds[i].startswith(prefix):
cmds[i-1] += '\n'+cmds.pop(i)
print(cmds)
Run Code Online (Sandbox Code Playgroud)
但你的答案似乎更整洁,更有效率.非常感谢大家
我建议您创建一个新列表,如您在问题规范中所示:
prefix = '!'
cmds = ['!test','hello','world','!echo','!embed','oh god']
output = []
for cmd in cmds:
if cmd.startswith(prefix) or not output:
output.append(cmd)
else:
output[-1] += "\n" + cmd # change the string in the last element of output
Run Code Online (Sandbox Code Playgroud)
结果是:
>>> output
['!test\nhello\nworld', '!echo', '!embed\noh god']
Run Code Online (Sandbox Code Playgroud)