The following code partitions a list in spaces of 5.
o_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
def partition(lst, size):
for i in range(0, len(lst), size):
yield lst[i :: size]
# size of each partition
n = 5
p_list = list(partition(o_list, n))
print("Original List: ")
print(o_list)
print("Partitioned List:")
print(p_list)
The following are the results:
Original List:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
Partitioned List:
[[10, 60, 110, 160], [60, 110, 160], [110, 160], [160]]
However I want the second array to be [20, 70, 120, 170] and the third and so on follow suit.
>Solution :
Just replace the comma in the range function to a // operator:
o_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
def partition(lst, size):
for i in range(0, len(lst) // size):
yield lst[i :: size]
# size of each partition
n = 5
p_list = list(partition(o_list, n))
print("Original List: ")
print(o_list)
print("Partitioned List:")
print(p_list)
This prints:
Original List:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
Partitioned List:
[[10, 60, 110, 160], [20, 70, 120, 170], [30, 80, 130, 180], [40, 90, 140, 190]]