Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to chain tuple in a list by the next item value

How can I get expected result from the list of tuple in Python 3?

[('I', 'N'),('love', 'V'),('Miley', 'N'),('Cyrus', 'N'),('but', 'ADV'),('hate', 'V'),('Liam', 'N'),('Hemsworth', 'N')]

Expected results:

['I', 'love', 'Miley Cyrus', 'but', 'hate', 'Liam Hemsworth']
like image 793
KitKit Avatar asked Jan 26 '23 05:01

KitKit


1 Answers

You could use itertools.groupby to group by the second element, then extract the first element of each group:

from itertools import groupby
from operator import itemgetter

data = [('I', 'N'), ('love', 'V'), ('Miley', 'N'), ('Cyrus', 'N'), ('but', 'ADV'), ('hate', 'V'), ('Liam', 'N'),
        ('Hemsworth', 'N')]

result = [' '.join(t[0] for t in group) for k, group in groupby(data, key=itemgetter(1))]

print(result)

Output

['I', 'love', 'Miley Cyrus', 'but', 'hate', 'Liam Hemsworth']

The above list comprehension is equivalent to the following for loop:

result = []
for k, group in groupby(data, key=itemgetter(1)):
    result.append(' '.join(t[0] for t in group))
like image 81
Dani Mesejo Avatar answered Jan 27 '23 18:01

Dani Mesejo