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

Grouping a list of list of tuple

I have a list of list of tuples, for example:

lst = [[1, 4, (1, 1, 1, 4)], [7,8,(2, 1,6, 14)],[2,3, (1, 1, 1, 9)], [5,4, (2, 1,1, 12)], [8,9, (2, 1,1, 99)],  [5,7,(2, 1,6, 19)], [3,4, (1, 1, 1, 14)]]

I need to group the list based on the tuple so that all the lists that only their last item in the tuple are different, will be in the same group. For instance:

first group: [[1, 4, (1, 1, 1, 4)], [2,3, (1, 1, 1, 9)], [3,4, (1, 1, 1, 14)]]
second group: [[5,4, (2, 1,1, 12)], [8,9, (2, 1,1, 99)]]
third group: [[7,8,(2, 1,6, 14)], [5,7,(2, 1,6, 19)]]

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

>Solution :

Try:

lst = [
    [1, 4, (1, 1, 1, 4)],
    [7, 8, (2, 1, 6, 14)],
    [2, 3, (1, 1, 1, 9)],
    [5, 4, (2, 1, 1, 12)],
    [8, 9, (2, 1, 1, 99)],
    [5, 7, (2, 1, 6, 19)],
    [3, 4, (1, 1, 1, 14)],
]

out = {}
for i in lst:
    *key, _ = i[-1]
    out.setdefault(tuple(key), []).append(i)

print(list(out.values()))

Prints:

[
    [[1, 4, (1, 1, 1, 4)], [2, 3, (1, 1, 1, 9)], [3, 4, (1, 1, 1, 14)]],
    [[7, 8, (2, 1, 6, 14)], [5, 7, (2, 1, 6, 19)]],
    [[5, 4, (2, 1, 1, 12)], [8, 9, (2, 1, 1, 99)]],
]
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