使用特定值填充python中的列表

2024-06-16 10:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

Tags: to实例方法inself元素列表some
3条回答

为什么不创建一个小的实用函数呢?

>>> 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的片相当于:

out.__setitem__(slice(0, len(x)), x)

或:

operator.setitem(out, slice(0, len(x)), x)

相关问题 更多 >