0

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?

1
  • 1
    Is the pattern that any items adjacent to one another should be joined as long as they aren't an x? Commented Apr 9, 2020 at 1:47

2 Answers 2

4
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']
>>> 
Sign up to request clarification or add additional context in comments.

3 Comments

This is better than mine! Didn't know about itertools.groupby
If there are several "x" in a row, you delete all but one of them. Why?
@HeapOverflow That's true, 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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.