Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python3中使用输入生成矩阵而不使用numpy_Python 3.x_Matrix_Input_Range_Sequence - Fatal编程技术网

Python 3.x 在Python3中使用输入生成矩阵而不使用numpy

Python 3.x 在Python3中使用输入生成矩阵而不使用numpy,python-3.x,matrix,input,range,sequence,Python 3.x,Matrix,Input,Range,Sequence,我想有两个输入:a,b或x,y,无论什么。。。 当用户输入说 3 5 然后shell应该打印一个3行5列的矩阵,并且应该用自然数(数字顺序从1开始,而不是0)填充矩阵。 例如: 输入:22 输出:[1,2] [3,4]Numpy库提供了重塑()函数,它可以实现您所需要的功能 from numpy import * #import numpy, you can install it with pip n = int(input("Enter number of rows: ")) #As

我想有两个输入:a,b或x,y,无论什么。。。 当用户输入说

3 5
然后shell应该打印一个3行5列的矩阵,并且应该用自然数(数字顺序从1开始,而不是0)填充矩阵。 例如:

输入:
22

输出:
[1,2]

[3,4]

Numpy库提供了重塑()函数,它可以实现您所需要的功能

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")

如果您的目标只是获得该格式的输出

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)

上面写着“垫子”没有定义。很抱歉有个打字错误。我已经编辑了代码。希望这次能奏效。@WiserDivisorth这个命中率非常接近我想要的!谢谢你,斯里纳波先生!如果我不想用括号怎么办?like::1,2/n 3,4更改要打印的最后一个打印语句(*列表)我编辑了答案。下面是没有库的代码:)希望有帮助。