简体   繁体   中英

Separate a List in 2 or more lists

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM