簡體   English   中英

在python中打印等距列表的最干凈方法是什么?

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

如果這是重復項,請關閉,但是此答案不能回答我的問題,因為我想打印列表,而不是列表中的元素。

例如,下面的方法不起作用:

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

所需的輸出:

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

基本上,如果列表中的所有項目都為n位或更少,則相等的間距將使每個項目在打印輸出中具有n+1點。 就像C ++中的setw 假設n是已知的。

如果我錯過了類似的SO問題,請隨時投票關閉。

您可以按照以下示例利用格式。 如果您真的需要方括號,那么您將不得不擺弄一些

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
items=range(10)
''.join(f'{x:3}' for x in items)
'  0  1  2  3  4  5  6  7  8  9'

如果沒有其他答案有效,請嘗試以下代碼:

    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)

我認為這是目前為止最好的方法,因為它允許您隨意操作列表。 甚至在數值上。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM