简体   繁体   中英

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

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.

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

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM