在python中填充具有特定值的列表 [英] Padding a list in python with particular value

查看:241
本文介绍了在python中填充具有特定值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
一些内置在python中填充列表的

Possible Duplicate:
Some built-in to pad a list in python

我有一个方法将返回包含4个元素的列表(实例变量). 另一种方法是将值分配给列表.

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

但是目前我不能保证列表被要求包含4个元素,所以我想用0填充它.

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.

除了说一个循环外,是否有其他方法可以用0填充它?

Is there a way to fill it with 0's other than say 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.

另一种可能性是:

self.myList = (self.myList + [0] * 4)[:4]

这篇关于在python中填充具有特定值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆