如何在Python3中输入2d数组中的元素

时间:2017-09-21 15:03:13

标签: python arrays python-3.x matrix multidimensional-array

如下面的C ++代码,我如何使用Python在2d Array中输入元素。请帮助在Python3中编写相同的程序。

int main()
{
 int s = 3;
 int a[s][s];
 cout<<"Enter 9 Element in Square Matrix";
 for(int i =0;i<s;i++)
 {
  for(int j =0; j<s;j++)
  {
   cin>>a[i][j];
  }
 }
 cout<<"You Entered";
 for(int i =0;i<s;i++)
 {
  for(int j =0; j<s;j++)
  {
   cout<<a[i][j]<<"\t";
  }
 cout<<endl;
 }
return 0;
}
Output:
Enter 9 Elements in Square Matrix
1
2
3
4
5
6
7
8
9
You Entered: 
1 2 3
4 5 6
7 8 9

如果程序中有错误,请不要尝试纠正。 谢谢。

4 个答案:

答案 0 :(得分:3)

我会在这里使用list存储2D数组。您可以使用许多其他结构来存储2D阵列,但是对于基本需求,这就足够了。

n=int(input("Enter N for N x N matrix : "))         #3 here
l=[]                                                #use list for storing 2D array

#get the user input and store it in list (here IN : 1 to 9)
for i in range(n): 
  row_list=[]                                      #temporary list to store the row
  for j in range(n): 
     row_list.append(int(input()))                 #add the input to row list
  l.append(row_list)                               #add the row to the list

print(l)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array
for i in range(n):
  for j in range(n):
    print(l[i][j], end=" ")
  print()                                           #new line

'''
1 2 3 
4 5 6 
7 8 9 
'''

答案 1 :(得分:1)

s = 3
a = [x[:] for x in [[0] * s] * s]

print("Enter 9 Element in Square Matrix")

for i in range(0, s):
    for j in range(0, s):
        a[i][j] = input()

print("You Entered")

for i in range(0, s):
    line = ''
    for j in range(0, s):
        line += a[i][j] + ' '
    print(line)

答案 2 :(得分:1)

如果你不熟悉python,你应该创建一个名为 matrix.py 的文件,然后添加以下内容:

matrix_size = 3
matrix = []

print("Enter {} Elements in Square Matrix:".format(matrix_size))
for i in range(0, matrix_size):
    row = []
    for j in range(0, matrix_size):
        row.append(input())
    matrix.append(row)

print("You entered:")
for i in range(0, matrix_size):
    print(" ".join(matrix[i]))

保存文件后,您可以这样执行此文件:

python3 matrix.py

以下是示例输出:

[martin@M7 tmp]$ python3 matrix.py
Enter 3 Elements in Square Matrix:
1
2
3
1
2
3
7
5
4
You entered:
1 2 3
1 2 3
7 5 4

答案 3 :(得分:0)

假设您要创建3 * 3矩阵:

按如下所示初始化矩阵:

matrix = [x[:] for x in [[0] * 0] * 0]

然后将矩阵元素作为用户输入:

    for i in range(0,3):
        row_list = []
        for j in range(0,3):
            row_list.append(int(input()))
        matrix.append(row_list)