-1

If I have the following list of lists for example:

 [['A', 'B', 'C'], ['A', 'D', 'E', 'B', 'C']]

How could I get a List with lists of only 3 elems each (in case they are greater than 3 elems), if they have not more than 3 elems we don't need to do nothing, we just need to separate the elems with more than 3 like the following:

[['A', 'B', 'C'], ['A', 'D', 'E'], ['D', 'E', 'B'], ['E', 'B', 'C']]

Could you help me with this ? I've been trying for a long time without success, kinda new to Python.

Edit: Well, I resolved this in this way:

def separate_in_three(lista):
    paths = []
    for path in lista:
        if len(path) <= 3:
            paths.append(path)
        else:
            for node in range(len(path)-1):
                paths.append(path[:3])
                path.pop(0);
                if(len(path) == 3):
                    paths.append(path)
                    break
    return paths

Seems to resolve my problem, I could use the list in comprehension, were it would be much more efficient than the way I did ? Thanks for the help btw !

1 Answers1

0

you can use list comprehension like below.

l =  [['A', 'B', 'C'], ['A', 'D', 'E', 'B', 'C','Z']]
[l[0]] + [l[1][i: i+len(l[0])] for i in range(1 + len(l[1]) - len(l[0]))]
Paras Gupta
  • 174
  • 4