我想要两个输入:a,b或x,y无论什么......当用户输入时说,
3 5
然后shell应该打印一个包含3行和5列的矩阵,它也应该用自然数填充矩阵(数字序列从1开始而不是0)。例::
IN:2 2
OUT:[1,2]
[3,4]
如果您的目标只是以该格式获得输出
n,m=map(int,input().split())
count=0
for _ in range(0,n):
list=[]
while len(list) > 0 : list.pop()
for i in range(count,count+m):
list.append(i)
count+=1
print(list)
我将尝试不使用numpy库。
row= int(input("Enter number of rows"))
col= int(input("Enter number of columns"))
count= 1
final_matrix= []
for i in range(row):
sub_matrix= []
for j in range(col):
sub_matrix.append(count)
count += 1
final_matrix.append(sub_matrix)
Numpy库提供了reshape()函数,可以完全满足您的需求。
from numpy import * #import numpy, you can install it with pip
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = range(1, n*m+1) #You want the range to start from 1, so you pass that as first argument.
x = reshape(x,(n,m)) #call reshape function from numpy
print(x) #finally show it on screen
编辑
如果你不想像评论中指出的那样使用numpy,这里是另一种解决问题的方法,没有任何库。
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = 1 #You want the range to start from 1
list_of_lists = [] #create a lists to store your columns
for row in range(n):
inner_list = [] #create the column
for col in range(m):
inner_list.append(x) #add the x element and increase its value
x=x+1
list_of_lists.append(inner_list) #add it
for internalList in list_of_lists: #this is just formatting.
print(str(internalList)+"\n")