Home > Mobile >  Partition a list on python
Partition a list on python

Time:04-12

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.

CodePudding user response:

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

CodePudding user response:

Something like this?

o_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]

[o_list[x::5] for x in range(len(o_list)//5)]

[[10, 60, 110, 160],
 [20, 70, 120, 170],
 [30, 80, 130, 180],
 [40, 90, 140, 190]]

CodePudding user response:

With division you can figure out how many slices can be produced, then simply produce those slices in a loop.

partition = lambda L, N: [L[n::N] for n in range(len(L)//N)]

print(partition(list(range(10, 201, 10)), 5))

#[[10, 60, 110, 160], [20, 70, 120, 170], [30, 80, 130, 180], [40, 90, 140, 190]]
  • Related