开发者

Padding a list in python with particular value [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Some built-in to pad a list in python

I have a method that will return a list (instance variable) with 4 elements. Another method is used to assign values to the list.

But at the moment I can't guarantee that the list has 4 elements when it's asked for, so I want to fill it up with 0's.

Is there a way to fill it with 0's other than sa开发者_如何学运维y a loop?

for i in range(4 - len(self.myList)):
   self.myList.append(0)


self.myList.extend([0] * (4 - len(self.myList)))

This works when padding with integers. Don't do it with mutable objects.

Another possibility would be:

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]

Assigning x to a slice of out is equivalent to:

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

or:

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


Why not create a little utility function?

>>> 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]
>>> 


Another way, using itertools:

from itertools import repeat
self.my_list.extend(repeat(0, 4 - len(self.my_list)))


l = object.method()
l = l + [0 for _ in range(4 - len(l))]


self.my_list.extend([0 for _ in range(4 - len(self.my_list))])


A hacky append-and-cut solution:

>>> x = [1,2]
>>> (x + [0] * 4)[:4]
[1, 2, 0, 0]

Or:

>>> (x + [0] * (4 - len(x)))
[1, 2, 0, 0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜