Lets say I've the following list, ['x','alpha','bravo','charlie','x','jack','x','mango','norway']
And I would want the following output ['x','alpha,bravo,charlie','x','jack','x','mango,norway']
How can I achieve this?
Lets say I've the following list, ['x','alpha','bravo','charlie','x','jack','x','mango','norway']
And I would want the following output ['x','alpha,bravo,charlie','x','jack','x','mango,norway']
How can I achieve this?
from itertools import groupby
items = ["x", "alpha", "bravo", "charlie", "x", "jack", "x", "mango", "norway"]
print([",".join(group) if key else "x" for key, group in groupby(items, key=lambda i: i != "x")])
Output:
['x', 'alpha,bravo,charlie', 'x', 'jack', 'x', 'mango,norway']
>>>
itertools.groupby does behave in this way. I wonder if it's a case the OP needs to take into account? In that case this solution would not be suitable.If the pattern I described is correct, try something like this:
mylist = ['x','alpha','bravo','charlie','x','jack','x','mango','norway']
mynewlist = []
for i in mylist:
if len(mynewlist) == 0 or i == 'x' or mynewlist[-1] == 'x':
mynewlist.append(i)
else:
mynewlist[-1] += ("," + i)
mynewlist