Split a list into list of lists based on modulus of index in Python
Question:
I’d like to write elements of lists to alternating files, and figured I would process the list before.
With a list of strings where the order is important, like ordered_favorite_colors
=["red", "blue", "green", "hazel"]
, and variable number of files number_of_files
, I’d like to partition the list into multiple lists so that each file can contain my most favorite color remaining. If number_of_files = 1
, the result would be [["red", "blue", "green", "hazel"]]
, if number_of_files = 3
the result would be [["red", "hazel"], ["blue"], ["green"]]
Answers:
l = [0, 1, 2, 3, 4, 5, 6]
size = 3
res = [l[i::size] for i in range(size)]
I’d like to write elements of lists to alternating files, and figured I would process the list before.
With a list of strings where the order is important, like ordered_favorite_colors
=["red", "blue", "green", "hazel"]
, and variable number of files number_of_files
, I’d like to partition the list into multiple lists so that each file can contain my most favorite color remaining. If number_of_files = 1
, the result would be [["red", "blue", "green", "hazel"]]
, if number_of_files = 3
the result would be [["red", "hazel"], ["blue"], ["green"]]
l = [0, 1, 2, 3, 4, 5, 6]
size = 3
res = [l[i::size] for i in range(size)]