创建一个以2位数字X,Y为输入的程序,生成一个二维数组

2024-03-29 10:03:36 发布

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

我需要将row(x)column(y)的数字作为用户输入,用逗号等分隔,并从中创建一个2D数组。 其中array[x][y]=x*j

这就是我要尝试的:

userInput = raw_input("Enter values for row and column number:\t").split(",")
for x in range(userInput):
    for y in range(userInput[x]):
        userInput[x][y]=x*y
        print(userInput[x][y])

Tags: 用户inforinputrawrangecolumn数字
2条回答

可以使用嵌套列表:

X, Y = raw_input("Enter values for row and column number:\t").split(",")

X = int(X)
Y = int(Y)
array = [[x*y for y in range(Y)] for x in range(x)]

第一行将为行和列输入的值绑定到XY。这些是字符串,因此它们被转换为整数,以便在range()中使用。最后,列表理解将创建表示为列表列表的“数组”。你知道吗

你的代码有几个问题。你知道吗

当你读用户输入时,你会得到字符串。如果你想用这个输入做算术运算,你必须把它转换成数字。你知道吗

您的代码有点混乱,因为您使用userInput作为初始用户输入,但是您尝试将其用于正在构建的数字网格。你知道吗

您试图在userInput[x][y]存在之前设置它,这样就行不通了。使用Python列表的通常方法是在列表末尾添加内容。你知道吗

这是您的代码的修改版本。你知道吗

from __future__ import print_function

user_input = raw_input("Enter values for row and column number: ")
rows, cols = user_input.split(",")
rows = int(rows)
cols = int(cols)

grid = []
for x in range(rows):
    row = []
    for y in range(cols):
        row.append(x * y)
    grid.append(row)
    print(row)

print()
print(grid)

演示

Enter values for row and column number: 4,5
[0, 0, 0, 0, 0]
[0, 1, 2, 3, 4]
[0, 2, 4, 6, 8]
[0, 3, 6, 9, 12]

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12]]

顺便说一句,既然您刚刚开始学习Python,那么您应该学习python3。如果你真的需要的话,你可以回头学习老式的python2。你知道吗

相关问题 更多 >