python - How do I repeatedly shift and pad elements in a list to get a list of lists? -
i have list a = [1, 2, 3, ..., n]
, want repeatedly shift list list of lists. first row should a
, second row [2, 3, 4, ...]
, third row [3, 4, 5, ...]
, until last row [n, 0, 0, ...]
. missing elements in last columns should zeros. trying put them individually, n >= 100 manually padding zeros take long. how do this?
edit same question numpy arrays, have.
>>> = [1, 2, 3, 4] >>> [ a[i:] + i*[0] in range(len(a))] [[1, 2, 3, 4], [2, 3, 4, 0], [3, 4, 0, 0], [4, 0, 0, 0]]
how works
to i'th shifted list, can use: a[i:] + i*[0]
. list comprehension repeatedly i's need.
using numpy
+
means different numpy arrays normal python lists. consequently, above code needs tweaks adapt numpy:
>>> import numpy np >>> = np.arange(1, 5) >>> [ np.concatenate((a[i:], np.zeros(i))) in range(len(a))] [array([1, 2, 3, 4]), array([2, 3, 4, 0]), array([3, 4, 0, 0]), array([4, 0, 0, 0])]
if want final result numpy array:
>>> np.array([np.concatenate((a[i:], np.zeros(i))) in range(len(a)) ]) array([[ 1., 2., 3., 4.], [ 2., 3., 4., 0.], [ 3., 4., 0., 0.], [ 4., 0., 0., 0.]])
Comments
Post a Comment