【问题标题】:Making a matrix in python 3 without numpy using inputs使用输入在没有numpy的python 3中制作矩阵
【发布时间】:2018-09-06 13:53:57
【问题描述】:

我想要两个输入:a,b 或 x,y 随便什么... 当用户输入说,

3 5

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

输入:2 2

输出:[1,2] [3,4]

【问题讨论】:

    标签: python-3.x matrix input range sequence


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 这非常接近我想要的!谢谢斯里纳布先生!
    • 如果我想不带括号怎么办?喜欢 :: 1, 2/n 3,4
    • 把最后一个打印语句改成 print(*list)
    【解决方案2】:

    我将尝试不使用 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)
    

    【讨论】:

    • 它说'mat'没有定义。
    • 很抱歉有错字。我已经编辑了代码。希望这次能奏效。 @WISERDIVISOR
    【解决方案3】:

    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
    

    编辑

    如果您不想像 cmets 中指出的那样使用 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")
    

    【讨论】:

    • 我编辑了答案。没有库的代码在它下面:) 希望它有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2015-03-30
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 2020-05-11
    相关资源
    最近更新 更多