如何在Python中限制表格中的列

时间:2018-12-26 14:21:51

标签: python list for-loop tabular

这是我的代码,用于打印从500到该数字的数字的产品:

num = int(input("Enter a number: "))
table = []
if num > 0:
    for i in range(1,500):
        prod = num * i
        if prod >= 500:
            break
        table.append(prod)
k = len(table)
j = 0
while j < len(table):
    print(table[k-1],end=" ")
    k = k - 1
    j = j + 1

这是输出:

Enter a number: 40
480 440 400 360 320 280 240 200 160 120 80 40 

现在,如您所见,这些数字连续一行打印。有什么办法可以将输出做成表格形式,最多包含六列?

3 个答案:

答案 0 :(得分:0)

尝试一下:

>>> table = [480, 440, 400, 360, 320, 280, 240, 200, 160, 120, 80, 40, 520]
>>> for i in range((len(table)//6)+1):
...    print(*table[i*6:(i+1)*6])
...    if len(table)%6 != 0 and len(table)//6 == i:
...       print(*table[(i+1)*6:])
... 
480 440 400 360 320 280
240 200 160 120 80 40
520

编辑:

您需要一个限制为六列的反向列表,因此请尝试以下操作:

table.reverse() # it revreses the list
size = 6        # it's the size of limitation

# it splits the list into 2D list with limitation of "size"
limited_table = [table[i:i+size] for i  in range(0, len(table), size)]

for x in limited_table:
    print(*x)

答案 1 :(得分:0)

tab[::-1]返回相反的列表。

for i, val in enumerate(tab[::-1]):
    print(val, end=' ')
    if i and not i % 6:
        print()

答案 2 :(得分:0)

只需将您的AttributeError: 'NoneType' object has no attribute 'has_header'更改为此:

for

输出将是一个二维列表,如下所示:

for index,i in enumerate(range(num ,500, num)):
    if index % 6 ==0:
        table.append([])
    table[-1].append(i)

并用于打印:

[[40, 80, 120, 160, 200, 240], [280, 320, 360, 400, 440, 480]]