Merge list item with previous list item

  • A+

I'm trying to merge list items with previous items if they don't contain a certain prefix, and adding a /n between said list items when doing so.

prefix  = '!' cmds    = ['!test','hello','world','!echo','!embed','oh god']  output  = ['!test/nhello/nworld','!echo','!embed/noh god'] 

I tried something like

for i in list(range(0,len(cmds))):     if not cmds[i+1].startswith(prefix):         cmds[i] += cmds.pop(i+1) 

but always get the list index out of range error.

My apologies if this is badly worded, or seems like an obvious fix, I'm fairly new to python/programming.


I had managed to get it to work with

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) 

but your answers seem so much neater and efficient. Much thanks everyone


I propose to create a new list, as you showed in your problem specification:

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 

The result is:

>>> output ['!test/nhello/nworld', '!echo', '!embed/noh god'] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: