N
N
Nicotrinity2021-12-24 03:15:46
Python
Nicotrinity, 2021-12-24 03:15:46

Merging elements in a Python list. How to merge matching elements into one list?

Merging elements in a Python list
Let's say I have a list in python like this:

Message = ['Owl: Fly away', 'Owl: Find a wise solution', 'Eeyore: Scream Loud', 'Winnie the Pooh: Go away ', 'Winnie the Pooh: Climb a tree']

How would I combine the list so that it becomes:

message = ['Owl: Fly away, find a wise solution', 'Eeyore: Scream loudly', 'Winnie the Pooh: Get away visit, Climb a tree']

Here, first you need to find a match and then merge ? I don't quite understand how to do this.

Ps Though head against the wall

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-12-24
@Nikotrinity

message = ['Сова: Улететь', 'Сова: Найти мудрое решение', 'Ослик Иа: Громко кричать', 'Винни-Пух: Уйти в гости', 'Винни-Пух: Залезть на дерево']
d = {}
for s in message:
    k, w = s.split(': ')
    d[k] = d[k] + ', ' + w if k in d else w
print(['%s: %s' % (k, w) for k, w in d.items()])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question