Pad list in Python

你说的曾经没有我的故事 提交于 2019-12-10 05:17:19

问题


How can I pad a list when printed in python?

For example, I have the following list:

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)

But how can I pad it to four indices with 'x's, so the output is like:

foo, bar, x, x

回答1:


In [1]: l = ['foo', 'bar']

In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'

The ['x'] * (4 - len(l)) produces a list comprising the correct number of 'x'entries needed for the padding.

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.




回答2:


Another possibility using itertools:

import itertools as it

l = ['foo', 'bar']

', '.join(it.islice(it.chain(l, it.repeat('x')), 4))



回答3:


Based on the grouper() recipe from itertools:

>>> L = ['foo', 'bar']
>>> ', '.join(next(izip_longest(*[iter(L)]*4, fillvalue='x')))
'foo, bar, x, x'

It probably belongs in the "don't try it at home" category.



来源:https://stackoverflow.com/questions/7714287/pad-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!