如何在Python3中以行和列显示数字序列?

2024-05-08 14:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个编码任务来输入行和列的长度,并创建一个幂表。下面的例子是5行5列。在

enter image description here

到目前为止,我的代码打印出正确的行数和列数,但我无法使计算正常工作。它只显示一张1的表,5乘5。在

rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1

Tags: columnsof代码number编码inputline例子
3条回答

以下是一种无论发生什么情况都能保持填充的方法:

def grid(rows, cols, padding):
  max_num_len = len(str(rows**cols))
  return '\n'.join([
    ''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
             for col in range(cols)])
    for row in range(rows)
  ])

print(grid(5, 5, 3))

相反,请尝试在Python中创建2D数组,例如2D list。在

Matrix = [[0 for x in range(5)] for y in range(5)] 
    for i in range(5):
        for j in range(5):
            Matrix[i][j]=j^i

然后,使用嵌套的for循环打印所需的数据。在

^{pr2}$

基本问题是需要嵌套循环。第二个问题是你永远不会改变y。现在你要做的是把1的幂序列计算成五条不同的行,然后你只打印最后一行的幂序列五次。尝试两种更改:

  1. 计算一条直线,然后立即打印出来。然后到下一行。在
  2. 使用正确的变量。在

变更后:

while z <= rows:
    while x <= cols:
        line = line + format(x**cols, "4d")   # Note the variable change
        x = x + 1
        print(line)

    z = z + 1

另外,请查找for语句,因为这将简化事情。之后,查找list comprehension以获得更多的压缩。在

相关问题 更多 >