Home > Mobile >  how do you split a list into 3 lists, for each list in a list? Python Beginner
how do you split a list into 3 lists, for each list in a list? Python Beginner

Time:05-21

list1= [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]]

Result should be:

list2 = [[1,2,3],[4,5,6],[7,8,9],[1,2,3],[4,5,6],[7,8,9],[1,2,3],[4,5,6],[7,8,9]]

This should work for any list divisible by 3 as well.

list1 = [1,2,3,4,5,6,7,8,9]

Result:

list2 = [[1,2,3],[4,5,6],[7,8,9]]

I tried using:

list2 = [list1[i:i   n] for i in range(0,len(list1),n)]

No luck.

CodePudding user response:

Try this:

list2 = [lst[j: j   3] for lst in list1 for j in range(0, 7, 3)] 

A slightly more generic approach:

list2 = [lst[j: j   3] for lst in list1 for j in range(0, len(lst) - 2, 3)]

CodePudding user response:

Answer:

list_1 = [either Nested or not Nested]

check_list_type = any(isinstance(i, list) for i in list_1)

if check_list_type == True:
    split_list = [z[j: j   3] for z in list_1 for j in range(0, len(z) - 2, 3)]
if check_list_type == False:
    length = int(len(list_1)/3)
    split_list = [list_1[i:i   length] for i in range(0,len(list_1),length)]

print(split_list)

Allows you to split any list into 3 more lists. Enjoy! Thanks for the help.

  • Related