0

Let's say I have two lists:

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]

And I want to merge alike items next to each other in list one (call this list three)

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_three = ["Alex", "John", "Alex", "John"]

And list two turns into list four, which follows the "pattern" of merging items in list one:

list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]
list_four = ["Hi Are you there?", "Hello Alex!", "How are you John?", "I am good Alex How about yourself?"]

How would I do so? I found this: Remove adjacent duplicate elements from a list, but it doesn't handle multiple lists, and I don't want to remove items from the second list.

Edit: I found a thread where I can get all instances of an item in a list, the code they use is:

def all_indices(value, qlist):
indices = []
idx = -1
while True:
    try:
        idx = qlist.index(value, idx+1)
        indices.append(idx)
    except ValueError:
        break
return indices

Now if I do this for my code, I get two lists:

Alex = [0,1,3]
John = [2,4,5]

However, how can I write a function that would combine list_two[0] and list_two[1]? Or what if Alex = [0,1,2,3,4,5], how could I combine all of those into one item in a list?

TobyTobyo
  • 405
  • 2
  • 6
  • 20

1 Answers1

2

Another groupby solution:

from itertools import groupby

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]

l2iter = iter(list_two)
list_three, list_four = zip(*((key, ' '.join(next(l2iter) for whatever in grp)) for key, grp in groupby(list_one)))
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99