Search code examples
pythonpython-3.xpython-itertools

Looping within a list of list


I have a list of items (every item is a list again)

[
['a', 'v1', 'b', 'l']
['a', 'v2', 'b', 'm']
['a', 'v2', 'b, 'n']
['a', 'v3', 'b', 'o']
]

I want the output to be grouped by the second item for element (v's), again in a group of list, such that the output is

[[['a', 'v1', 'b', 'l']][['a', 'v2', 'b', 'm']['a', 'v2', 'b', 'n']][['a','v2','b','o']]]

Would appreciate for any response, how can I achieve the same in python. Not able to get the itertools to apply. Not sure itertools should be applied here not, if yes how? Else what other options can be achieved here.


Solution

  • itertools.groupy() is the right tool for this but keep in mind that the documentation says:

    Generally, the iterable needs to already be sorted on the same key function.

    from itertools import groupby
    from operator import itemgetter
    
    data = [
    ['a', 'v1', 'b', 'l'],
    ['a', 'v2', 'b', 'm'],
    ['a', 'v2', 'b', 'n'],
    ['a', 'v3', 'b', 'o'],
    ]
    
    data_sorted = sorted(data, key=itemgetter(1))
    for key, group in itertools.groupby(data_sorted, key=itemgetter(1)):
        print(list(group))
    

    outputs

    [['a', 'v1', 'b', 'l']]
    [['a', 'v2', 'b', 'm'], ['a', 'v2', 'b', 'n']]
    [['a', 'v3', 'b', 'o']]
    

    You can shorten that with a list expression:

    [list(group) for key, group in itertools.groupby(data_sorted, key=itemgetter(1))]
    

    gives

    [[['a', 'v1', 'b', 'l']], [['a', 'v2', 'b', 'm'], ['a', 'v2', 'b', 'n']], [['a', 'v3', 'b', 'o']]]