Python中的填充列表 [英] Pad list in Python
问题描述
用python打印时如何填充列表?
How can I pad a list when printed in python?
例如,我有以下列表:
mylist = ['foo', 'bar']
我想将此填充到带有逗号的四个索引中.我知道我可以执行以下操作以将其作为逗号和空格分隔的列表:
I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:
', '.join(mylist)
但是我如何用'x'将其填充到四个索引,所以输出就像:
But how can I pad it to four indices with 'x's, so the output is like:
foo, bar, x, x
推荐答案
In [1]: l = ['foo', 'bar']
In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'
['x'] * (4 - len(l))
会生成一个列表,其中包含填充所需的正确数量的'x'
条目.
The ['x'] * (4 - len(l))
produces a list comprising the correct number of 'x'
entries needed for the padding.
编辑有人质疑len(l) > 4
会发生什么.在这种情况下,['x'] * (4 - len(l))
结果为空列表,预期的.
edit There's been a question about what happens if len(l) > 4
. In this case ['x'] * (4 - len(l))
results in an empty list, as expected.
这篇关于Python中的填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!