What's the cleanest way to print an equally-spaced list in python?

我与影子孤独终老i 提交于 2021-02-19 23:08:35

问题


Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.

For example, the below does not work:

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)

Desired output:

[  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]

Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.

If I have missed a similar SO question, feel free to vote to close.


回答1:


You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit

lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

frmt = "{:>3}"*len(lst)

print(frmt.format(*lst))
  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15



回答2:


items=range(10)
''.join(f'{x:3}' for x in items)
'  0  1  2  3  4  5  6  7  8  9'



回答3:


If none of the other answers work, try this code:

    output = ''
    space = ''
    output += str(list[0])
    for spacecount in range(spacing):
        space += spacecharacter
    for listnum in range(1, len(list)):
        output += space
        output += str(list[listnum])
    print(output)



回答4:


I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.

mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))


来源:https://stackoverflow.com/questions/47735206/whats-the-cleanest-way-to-print-an-equally-spaced-list-in-python

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