2024-09-26 18:20:32 发布
网友
Possible Duplicate:Some built-in to pad a list in python
我有一个方法,它将返回一个包含4个元素的列表(实例变量)。 另一种方法用于将值赋给列表。
但目前我不能保证列表有4个元素,所以我想用0来填充它
有没有办法用0来填充它,而不是说一个循环?
for i in range(4 - len(self.myList)): self.myList.append(0)
为什么不创建一个小的实用函数呢?
>>> def pad(l, content, width): ... l.extend([content] * (width - len(l))) ... return l ... >>> pad([1, 2], 0, 4) [1, 2, 0, 0] >>> pad([1, 2], 2, 4) [1, 2, 2, 2] >>> pad([1, 2], 0, 40) [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>>
self.myList.extend([0] * (4 - len(self.myList)))
这在填充整数时有效。不要使用可变对象。
另一种可能性是:
self.myList = (self.myList + [0] * 4)[:4]
>>> out = [0,0,0,0] # the "template" >>> x = [1,2] >>> out[:len(x)] = x >>> print out [1, 2, 0, 0]
将x分配给out的片相当于:
x
out
out.__setitem__(slice(0, len(x)), x)
或:
operator.setitem(out, slice(0, len(x)), x)
为什么不创建一个小的实用函数呢?
这在填充整数时有效。不要使用可变对象。
另一种可能性是:
将
x
分配给out
的片相当于:或:
相关问题 更多 >
编程相关推荐