1

Given a

list = [0,1,2,3,4,5,6,7,8,9,10]

How can I get a 2D List like:

2dList = [[0,1,2,3],[2,3,4,5],[4,5,6,7],[6,7,8,9],[8,9,10]]

(each 1st dimension of "2dList" has 4 values, there is a "shift" of 2 values from "list". When there isn't 4 values to fulfill the 1st dimension, it just store the last values from "list"]

?

thanks!

kairos
  • 524
  • 4
  • 16

2 Answers2

2
my_list = [0,1,2,3,4,5,6,7,8,9,10]

move_amount = 2
slice_size = 4
print [my_list[i:i + slice_size] for i in range(
  0, len(my_list) - move_amount, move_amount)]
Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75
  • 1
    this outputs an extra `[10]` at the end. it can be debated as to whether it should be there or not, as it can be considered a valid piece of the output. To remove it, use `range(0, len(l) - move_amount, move_amount)` – njzk2 May 26 '14 at 19:48
  • oops, fixed. thanks. – Jesse Aldridge May 26 '14 at 19:49
2

IF you are willing to use numpy you can change the array strides in order to achieve what you want:

import numpy as np
from numpy.lib.stride_tricks import as_strided

a = np.array([0,1,2,3,4,5,6,7,8,9,10, 11]) # added 11 to avoid a memory mess
as_strided(a, shape=(5,4), strides=(a.strides[0]*2, a.strides[0]))
#array([[ 0,  1,  2,  3],
#       [ 2,  3,  4,  5],
#       [ 4,  5,  6,  7],
#       [ 6,  7,  8,  9],
#       [ 8,  9, 10,  11]])

and in memory this is actually what it is in array a, which can be useful for some purposes...

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234