你如何正确地格式化整数的多个列在python?

问题描述 投票:-2回答:2

我有一些代码在这里:

for i in range(self.size):
    print('{:6d}'.format(self.data[i], end=' '))
        if (i + 1) % NUMBER_OF_COLUMNS == 0:
            print()

眼下这个打印为:

1 1 1 1 1 2 3 3 3 3 (whitespace) 3 3 3 etc. 它创建了一个新的生产线时,命中10个数字,但它好好尝试在连续打印最初的10 ...

这就是我要的-

1 1 1 1 1 1 1 2 2 3
3 3 3 3 3 4 4 4 4 5

然而,当它击中两位数字也得到弄糟 -

8 8 8 8 8 9 9 9 9 10
10 10 10 10 10 10 etc.

我希望它是右对齐喜欢这个 -

  8  8  8  8  8  9
 10 10 10 10 11 12 etc.

当我删除格式片,将打印的行出来,但不会是多余的间距在那里当然!

python
2个回答
0
投票

您可以对齐使用字符串的方法.rjust“填充”值的字符串。使用一些虚拟数据:

NUMBER_OF_COLUMNS = 10
for i in range(100):
    print("{}".format(i//2).rjust(3), end=' ')
    #print("{:3}".format(i//2), end=' ') edit: this also works. Thanks AChampion
    if (i + 1) % NUMBER_OF_COLUMNS == 0:
        print()

#Output:
  0   0   1   1   2   2   3   3   4   4 
  5   5   6   6   7   7   8   8   9   9 
 10  10  11  11  12  12  13  13  14  14 
 15  15  16  16  17  17  18  18  19  19 
 20  20  21  21  22  22  23  23  24  24 
 25  25  26  26  27  27  28  28  29  29 
 30  30  31  31  32  32  33  33  34  34 
 35  35  36  36  37  37  38  38  39  39 
 40  40  41  41  42  42  43  43  44  44 
 45  45  46  46  47  47  48  48  49  49 

0
投票

另一种方法是只在数据块成行和打印的每一行,例如:

def chunk(iterable, n):
    return zip(*[iter(iterable)]*n)

for row in chunk(self.data, NUMBER_OF_COLUMNS):
    print(' '.join(str(data).rjust(6) for data in row))

e.g:

In []:
for row in chunk(range(100), 10):
    print(' '.join(str(data//2).rjust(3) for data in row))

Out[]:
  0   0   1   1   2   2   3   3   4   4
  5   5   6   6   7   7   8   8   9   9
 10  10  11  11  12  12  13  13  14  14
 15  15  16  16  17  17  18  18  19  19
 20  20  21  21  22  22  23  23  24  24
 25  25  26  26  27  27  28  28  29  29
 30  30  31  31  32  32  33  33  34  34
 35  35  36  36  37  37  38  38  39  39
 40  40  41  41  42  42  43  43  44  44
 45  45  46  46  47  47  48  48  49  49
© www.soinside.com 2019 - 2024. All rights reserved.