一些内置在python中填充列表的功能 [英] Some built-in to pad a list in python

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

问题描述

我有一个< N ,我想用一个值将其填充到大小N.

I have a list of size < N and I want to pad it up to the size N with a value.

当然,我可以使用类似以下的内容,但是我觉得应该错过了一些东西:

Certainly, I can use something like the following, but I feel that there should be something I missed:

>>> N = 5
>>> a = [1]
>>> map(lambda x, y: y if x is None else x, a, ['']*N)
[1, '', '', '', '']

推荐答案

a += [''] * (N - len(a))

或者如果您不想就地更改a

or if you don't want to change a in place

new_a = a + [''] * (N - len(a))

您始终可以创建list的子类,并随便调用该方法

you can always create a subclass of list and call the method whatever you please

class MyList(list):
    def ljust(self, n, fillvalue=''):
        return self + [fillvalue] * (n - len(self))

a = MyList(['1'])
b = a.ljust(5, '')

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

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