Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Given a list of nested lists:

pairs = [['A', 'berries'], ['A', 'bannanas], ['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', 'bannanas]], 
  [['B', 'apples']], 
  [['C', 'oranges'], ['C', 'apricots'], ['C', 'tomatoes']]
]

So far I tried the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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', 'bannanas']]
[['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']]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading