一些内置在 python 中填充列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3438756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Some built-in to pad a list in python
提问by newtover
I have a list of size < Nand I want to pad it up to the size N with a value.
我有一个大小 < N的列表,我想用一个值将它填充到大小 N。
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, '', '', '', '']
采纳答案by John La Rooy
a += [''] * (N - len(a))
or if you don't want to change ain place
或者如果你不想a就地改变
new_a = a + [''] * (N - len(a))
you can always create a subclass of list and call the method whatever you please
您始终可以创建 list 的子类并随意调用该方法
class MyList(list):
def ljust(self, n, fillvalue=''):
return self + [fillvalue] * (n - len(self))
a = MyList(['1'])
b = a.ljust(5, '')
回答by Katriel
gnibbler's answer is nicer, but if you need a builtin, you could use itertools.izip_longest(zip_longestin Py3k):
gnibbler 的回答更好,但如果你需要一个内置函数,你可以使用itertools.izip_longest(zip_longest在 Py3k 中):
itertools.izip_longest( xrange( N ), list )
which will return a list of tuples ( i, list[ i ] )filled-in to None. If you need to get rid of the counter, do something like:
这将返回( i, list[ i ] )填充为 None的元组列表。如果您需要摆脱计数器,请执行以下操作:
map( itertools.itemgetter( 1 ), itertools.izip_longest( xrange( N ), list ) )
回答by kennytm
There is no built-in function for this. But you could compose the built-ins for your task (or anything :p).
没有为此的内置函数。但是您可以为您的任务(或任何东西:p)编写内置插件。
(Modified from itertool's padnoneand takerecipes)
(从 itertool'spadnone和takerecipes修改)
from itertools import chain, repeat, islice
def pad_infinite(iterable, padding=None):
return chain(iterable, repeat(padding))
def pad(iterable, size, padding=None):
return islice(pad_infinite(iterable, padding), size)
Usage:
用法:
>>> list(pad([1,2,3], 7, ''))
[1, 2, 3, '', '', '', '']
回答by Thierry
You could also use a simple generator without any build ins. But I would not pad the list, but let the application logic deal with an empty list.
您还可以使用没有任何内置插件的简单生成器。但是我不会填充列表,而是让应用程序逻辑处理空列表。
Anyhow, iterator without buildins
无论如何,没有构建的迭代器
def pad(iterable, padding='.', length=7):
'''
>>> iterable = [1,2,3]
>>> list(pad(iterable))
[1, 2, 3, '.', '.', '.', '.']
'''
for count, i in enumerate(iterable):
yield i
while count < length - 1:
count += 1
yield padding
if __name__ == '__main__':
import doctest
doctest.testmod()
回答by Federico
If you want to pad with None instead of '', map() does the job:
如果你想用 None 而不是 '' 填充,map() 可以完成这项工作:
>>> map(None,[1,2,3],xrange(7))
[(1, 0), (2, 1), (3, 2), (None, 3), (None, 4), (None, 5), (None, 6)]
>>> zip(*map(None,[1,2,3],xrange(7)))[0]
(1, 2, 3, None, None, None, None)
回答by aberger
To go off of kennytm:
离开 kennytm:
def pad(l, size, padding):
return l + [padding] * abs((len(l)-size))
>>> l = [1,2,3]
>>> pad(l, 7, 0)
[1, 2, 3, 0, 0, 0, 0]
回答by Nuno André
I think this approach is more visual and pythonic.
我认为这种方法更加直观和 Pythonic。
a = (a + N * [''])[:N]
回答by pylang
more-itertoolsis a library that includes a special paddedtool for this kind of problem:
more-itertools是一个包含padded解决此类问题的特殊工具的库:
import more_itertools as mit
list(mit.padded(a, "", N))
# [1, '', '', '', '']
Alternatively, more_itertoolsalso implements Python itertools recipesincluding padnoneand takeas mentioned by @kennytm, so they don't have to be reimplemented:
另外,more_itertools还实现了Python的itertools食谱,包括padnone和take由@kennytm提到的,这样他们就不必重新实现:
list(mit.take(N, mit.padnone(a)))
# [1, None, None, None, None]
If you wish to replace the default Nonepadding, use a list comprehension:
如果您希望替换默认None填充,请使用列表理解:
["" if i is None else i for i in mit.take(N, mit.padnone(a))]
# [1, '', '', '', '']
回答by Paul Crowley
extra_length = desired_length - len(l)
l.extend(value for _ in range(extra_length))
This avoids any extra allocation, unlike any solution that depends on creating and appending the list [value] * extra_length. The "extend" method first calls __length_hint__on the iterator, and extends the allocation for lby that much before filling it in from the iterator.
这避免了任何额外的分配,这与依赖于创建和附加列表的任何解决方案不同[value] * extra_length。“extend”方法首先调用__length_hint__迭代器,并l在从迭代器填充之前将分配扩展那么多。
回答by kederrac
you can use *iterable unpacking operator:
您可以使用*可迭代解包运算符:
N = 5
a = [1]
pad_value = ''
pad_size = N - len(a)
final_list = [*a, *[pad_value] * pad_size]
print(final_list)
output:
输出:
[1, '', '', '', '']

