In Python, how do you split a list into even pieces starting from the last element from the previous snippet?

What would be the most pythonic way to convert a list like:

mylist = [0,1,2,3,4,5,6,7,8] 

into fragments of n elements that always begin with the last element of the previous fragment. The last element of the last fragment must be identical to the first element of the first block to make the data structure circular. How:

 [ [0,1,2,3], [3,4,5,6], [6,7,8,0], ] 

under the assumption that len(mylist) % (n-1) == 0 . So it always works beautifully.

+4
source share
2 answers

How about a simple solution?

 splitlists = [mylist[i:i+n] for i in range(0, len(mylist), n-1)] splitlists[-1].append(splitlists[0][0]) 
+6
source

A less simple solution involving numpy (for the sake of excess):

 from numpy import arange, roll, column_stack n = 4 values = arange(10, 26) # values -> [10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25] idx = arange(0, values.size, n) # [ 0 4 8 12] idx = roll(idx, -1) # [ 4 8 12 0] col = values[idx] # [14 18 22 10] values = column_stack( (values.reshape(n, -1), col) ) [[10 11 12 13 14] [14 15 16 17 18] [18 19 20 21 22] [22 23 24 25 10]] 
0
source

Source: https://habr.com/ru/post/1432514/


All Articles