Search code examples
pythondata-structuresnested-lists

How to group the same "type elements" from a nested list of tuples?


Given a list of nested lists:

pairs = [['A', 'berries'], ['A', 'bananas'], ['B', 'apples'], ['C', 'oranges'], ['C', 'apricots'], ['C', 'tomatoes']]

How to nest the elements of the l by grouping them into "list types" such as (*):

[
  [['A', 'berries'], ['A', 'bananas']], 
  [['B', 'apples']], 
  [['C', 'oranges'], ['C', 'apricots'], ['C', 'tomatoes']]
]

So far I tried the following:

def get_type(e):
    return str(e[0])


for e in pairs:
    l = []
    if e[0] == get_type(e):
        l.append(e)
    else:
        pass

print(l)

However, the above is not grouping the elements of the same type:

[['A', 'berries']]
[['A', 'bananas']]
[['B', 'apples']]
[['C', 'oranges']]
[['C', 'apricots']]
[['C', 'tomatoes']]

Instead it is only appending each element into a new list insted of creating groups as (*).


Solution

  • You can use the groupby method from the itertools module:

    from itertools import groupby
    
    grouped_list = [list(group) for _, group in groupby(l, lambda x: x[0])]
    
    >>> grouped_list
    # [[['A', 'berries'], ['A', 'bannanas']], [['B', 'apples']], [['C', 'oranges'], ['C', 'apricots'], ['C', 'tomatoes']]]