Basj
Basj

Reputation: 46423

Auto zero-padding an array

Let L be a list of, say, 55 items :

L=range(55)
for i in range(6):
 print L[10*i:10*(i+1)]

The printed list will have 10 items for i = 0, 1, 2, 3 , 4, but for i = 5, it will have 5 items only.

Is there a quick method for auto zero-padding L[50:60] so that it is 10 items-long ?

Upvotes: 3

Views: 923

Answers (4)

Sam Hartman
Sam Hartman

Reputation: 6529

You can also build the intelligence into your objects. I have left out corner cases; this just illustrates the point.

class ZeroList(list):
    def __getitem__(self, index):
        if index >= len(self):c
            return 0
        else: return super(ZeroList,self).__getitem__(index)

    def __getslice__(self,i,j):
        numzeros = j-len(self)
        if numzeros <= 0:
            return super(ZeroList,self).__getslice__(i,j)
        return super(ZeroList,self).__getslice__(i,len(self)) + [0]*numzeros

>>> l = ZeroList(range(55))
>>> l[40:50]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>> l[50:60]
[50, 51, 52, 53, 54, 0, 0, 0, 0, 0]

Upvotes: 2

Exelian
Exelian

Reputation: 5888

This might look like wizardry, also please note that this create a tuple and not a list.

from itertools import izip_longest

L = range(55)
list_size = 10
padded = list(izip_longest(*[iter(L)] * list_size, fillvalue=0))
for l in padded:
    print l

For an explanation about the zip + iter trick see the documentation here

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

Using NumPy:

>>> a = np.arange(55)
>>> a.resize(60)
>>> a.reshape(6, 10)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54,  0,  0,  0,  0,  0]])

Upvotes: 7

falsetru
falsetru

Reputation: 369494

>>> L = range(55)
>>> for i in range(6):
...     print (L[10*i:10*(i+1)] + [0]*10)[:10]
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
[50, 51, 52, 53, 54, 0, 0, 0, 0, 0]

Upvotes: 4

Related Questions