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']
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With