Search code examples
pythonpython-3.xlistgroup-bygrouping

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)]]

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)]],
    ]