【问题标题】:How can I create x amount of lists based on user input? [duplicate]如何根据用户输入创建 x 个列表? [复制]
【发布时间】:2021-03-18 01:20:44
【问题描述】:

我必须编写一个程序,根据用户定义的维度创建方阵。因此,如果用户输入“3”作为维度,我希望我的程序显示 3 x 3 矩阵。我必须用 1 到 15 之间的随机数填充矩阵。到目前为止,我有这个:

dimension = int(input("Enter the number of rows and columns: \n")) 
import random
for i in range(1,dimension):
    randomMatrix = random.sample(range(1,16), dimension)
print(randomMatrix)

但是,它只显示矩阵的一行,而不是用户指定的全部。我不知道如何使循环变白,以便循环随机列表以按用户指定的尺寸创建随机矩阵。任何帮助将不胜感激。

【问题讨论】:

    标签: python loops matrix random


    【解决方案1】:

    我建议你使用numpy:

    import numpy as np
    
    dimension = int(input("Enter the number of rows and columns: \n")) 
    
    randomMatrix = np.random.randint(0,16, size=(dimension,dimension))
    
    print(randomMatrix)
    

    【讨论】:

    • 啊有道理,非常感谢。你刚刚救了我哈哈
    【解决方案2】:

    .append 到随机矩阵:

    dimension = int(input("Enter the number of rows and columns: \n"))
    import random
    randomMatrix = []
    for i in range(1,dimension):
         randomMatrix.append(random.sample(range(1,16), dimension))
    print(randomMatrix)
    

    如果允许使用 numpy,则不建议这样做,然后使用其他答案。

    【讨论】:

    • 谢天谢地我被允许使用 numpy 但无论如何谢谢:)
    【解决方案3】:

    您的代码看起来不错,如果您不想按照@godot 的建议使用numpy(我完全同意他的观点),您只需将每个列表存储在一个外部列表中,从而生成嵌套列表:

    dimension = int(input("Enter the number of rows and columns: \n")) 
    import random
    randomMatrix =[]
    for i in range(1,dimension):
        randomMatrix.append(random.sample(range(1,16), dimension))
    print(randomMatrix)
    
    >>> Enter the number of rows and columns: 
     5
    [[13, 2, 14, 4, 8], [7, 11, 4, 2, 8], [8, 15, 14, 13, 5], [10, 15, 2, 1, 12]]
    

    【讨论】:

    • 啊,好的,非常感谢。谢天谢地,我被允许使用 numpy :)
    猜你喜欢
    • 2022-11-24
    • 2020-04-29
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2022-01-20
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多