How to combine specific elements from a Python list?

Viewed 55

If I have a Python list, how can I combine some specific elements from the list?

My string looks like this:

my_string = ['Dog', 'Cat', 'And', 'Mouse', 'Whale', 'Cat', 'And', 'Mouse']

I want my new string to look like this:

new_string = ['Dog', 'Cat And Mouse', 'Whale', 'Cat And Mouse']

Here's my code so far (not correct):

new_string = iter(my_string)
my_string[:] = [i + next(new_string) if i == 'Cat' else i for i in new_string]

If I print my new string, I get:

['Dog', 'CatAnd', 'Mouse', 'Whale', 'CatAnd', 'Mouse']

Where am I going wrong? Thank you.

3 Answers

You have the right idea, just not going far enough — you are taking just one next element, when you want two. Also, you want a space between.

my_string[:] = [
    ' '.join(i, next(new_string), next(new_string)) if i == 'Cat' else i
    for i in new_string
]

Sliding over the word triplets in the list:

my_string = ['Dog', 'Cat', 'And', 'Mouse', 'Whale', 'Cat', 'And', 'Mouse']

new_string = []
x = 0

while x < len(my_string) - 2:
    triplet = my_string[x:x+3]

    if len(triplet) == 3: # we have a full triplet
        if triplet[1] == "And":
            new_string.append(' '.join(triplet))
            x += 3 # skip next two elements
        else:
            new_string.append(triplet[0])
            x += 1
    else: # we are approaching the end of the list
        new_string.extend(triplet)
        break

print(new_string)

produces:

['Dog', 'Cat And Mouse', 'Whale', 'Cat And Mouse']

Here is one approach. We can first form a single string of space separated words. Then, use re.findall to first search for two words separated by And, and that failing, just find a single word.

my_string = ['Dog', 'Cat', 'And', 'Mouse', 'Whale', 'Cat', 'And', 'Mouse']
output = re.findall(r'\w+ And \w+|\w+', ' '.join(my_string))
print(output)  # ['Dog', 'Cat And Mouse', 'Whale', 'Cat And Mouse']
Related