让L
成为55个项目的列表:
L=range(55)
for i in range(6):
print L[10*i:10*(i+1)]
打印列表将有10项i = 0,1,2,3,4,但对于i = 5,它只有5项。
有自动零填充L [50:60]的快速方法,所以它是10个项目吗?
答案 0 :(得分:7)
使用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]])
答案 1 :(得分:4)
>>> 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]
答案 2 :(得分:3)
这可能看起来像巫术,请注意,这会创建tuple
而不是列表。
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
有关zip
+ iter
技巧的说明,请参阅文档here
答案 3 :(得分:2)
您还可以在对象中构建智能。我遗漏了角落的情况;这只是说明了这一点。
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]