SoFunction
Updated on 2024-11-18

Python3 Ways to Split a List into Multiple Lists by a Specified Number of Lists

If we need to split a list into multiple lists by a specified number of lists: for example, [1,2,3,4,5,6,7,8,9,10] into [1,2,3][4,5,6][7,8,9][10], we can create a list splitting function split_list.py.

def list_of_groups(init_list, children_list_len):
  list_of_groups = zip(*(iter(init_list),) *children_list_len)
  end_list = [list(i) for i in list_of_groups]
  count = len(init_list) % children_list_len
  end_list.append(init_list[-count:]) if count !=0 else end_list
  return end_list

where children_list_len is the length of the children list you specify.

We can call this function in.

import split_list
 
code_list = ['300033','600066','300032','600065','300031','600064']
 
code_list = split_list.list_of_groups(code_list,3)

After adding the print, you'll see that the elements in code_list become a list, and to fetch them you just need to use code_list[i] (i = 0,1,2 ......)

The above Python3 way to split a list into multiple lists by a specified number is all I have to share with you, I hope it will give you a reference, and I hope you will support me more.