ChiChi
ChiChi

Reputation: 103

combine matching tuples elements with unique elements of other tuples

I would like to make a new list of tuples from the tuples that match other tuples on their first element. When the tuples match with another tuple on their first element I would also like to add the third element to the matching tuple.

Example of the data (tuples have 3 strings):

unique_3 = [(apple, banana, fruit),
           (apple, banana, dessert),
           (eggplant, fig, plant),
           (eggplant, fig, purple),
           (iris, jaguar, horse)]

The output I am looking for:

new_list =[(apple, banana, [fruit, dessert]), 
           (eggplant, fig, [plant, purple]),
           (iris, jaguar, horse)]

I only really need to match on the first element of the tuple. So I have tried this:

new_list= [next(i for i, v in enumerate(unique_3) if v[0] == any(v[0]))]  

which returns StopIteration without results, so I haven't gotten very far with building the new_list.

Upvotes: 1

Views: 566

Answers (1)

atru
atru

Reputation: 4744

You can use groupby to group the items based on the first element of each tuple,

from itertools import groupby

unique_sorted = sorted(unique_3, key = lambda x: x[0])

group_list = []
for key, group in groupby(unique_sorted, lambda x: x[0]):
        group_list.append(list(group))

new_list = [(x[0][0], x[0][1], [y[-1] for y in x]) for x in group_list]

At each for iteration, groupby returns groups of elements group with the same first tuple element, key. The elements have to be consecutive in order to be group, hence the original list is sorted in the first step based on the first value in each tuple.

Upvotes: 1

Related Questions