【发布时间】:2013-11-19 13:38:04
【问题描述】:
让L 成为一个列表,比如说,55 个项目:
L=range(55)
for i in range(6):
print L[10*i:10*(i+1)]
对于 i = 0, 1, 2, 3 , 4,打印的列表将有 10 个项目,但对于 i = 5,它将只有 5 个项目。
有没有快速自动补零 L[50:60] 的方法,使其长度为 10 项?
【问题讨论】:
让L 成为一个列表,比如说,55 个项目:
L=range(55)
for i in range(6):
print L[10*i:10*(i+1)]
对于 i = 0, 1, 2, 3 , 4,打印的列表将有 10 个项目,但对于 i = 5,它将只有 5 个项目。
有没有快速自动补零 L[50:60] 的方法,使其长度为 10 项?
【问题讨论】:
使用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]])
【讨论】:
resize 和reshape 步骤结合起来,然后执行a.resize(6, 10)。此外,由于 OP 似乎对打印感兴趣,也许更好的解决方案是 np.resize(a, (6, 10)),它返回调整大小的 copy 而不是修改原始数组。
np.resize 不会在数组末尾填充 0。
fill= 关键字,那就太好了。
>>> 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]
【讨论】:
pprint 会更好吗?
这可能看起来像魔法,还请注意,这会创建一个 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
【讨论】:
您还可以将智能构建到您的对象中。我遗漏了极端案例;这只是说明了这一点。
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]
【讨论】: