【问题标题】:How can I create a matrix in which the user inputs both rows and columns and then enters the values for each position in Python?如何创建一个矩阵,用户在其中输入行和列,然后在 Python 中输入每个位置的值?
【发布时间】:2021-05-29 18:40:10
【问题描述】:

这应该是代码的工作方式:

    n = int(input()) #number of rows, for example 3
    m = int(input()) #number of columns, for example 5

然后用户将在一行输入一个值,然后为列输入一个值。

    x = int(input()) #This should be the row number, for example row 1
    y = float(input()) #This should be the value for each position inside of each x.

x 和 y 都需要遵循某些条件,所以我将它们分开。理论上它应该是这样的:

    matrix = [ [0.4], [0.3, 0.2, 0.5], [0.7] ] #Row 1 has 1 float, Row 2 has 3 float and Row 3 only 1

一些浮点数将进入不同的行,例如第 1 行可以有来自输入的三个浮点数,而另一行(第 3 行)可能有来自输入的 5 个浮点数。

我尝试过使用以下循环:

    for i in range(n): #I have tried multiple ways using len function, append function, etc.
        for j in range(m):

但我似乎无法在矩阵上分配每个值,因为我必须确保输入遵循某些条件,因为程序应该读取与变量“m”一样多的不同浮点数。

我以这种方式详细说明代码的原因是因为我必须根据从浮点输入中获得的不同值计算平均值(在不同的函数中),使它们通过我已经拥有的公式以前做过。

【问题讨论】:

  • 如果用户在开始时必须输入m,列数,怎么可能有些行有更多列? m 应该只是每行的最大列数吗?
  • 嘿@He3lixxx,感谢您的回复!在这种情况下,m 变为用户将要输入的y 输入的数量。因此,如果 m = 5 将有 5 个不同的 y 输入,每个输入分配给由 n 数量确定的行号。我猜可能每列的其他位置为 0。

标签: python matrix input row multiple-columns


【解决方案1】:

据我了解,这应该是您所需要的:

row_input_count = int(input("please enter the number of rows you want to input: "))
column_count = int(input("please enter the number of columns: "))

matrix = []
for _ in range(row_input_count):
    row_index = -1
    while row_index < 0:
        row_index = int(input(f"please select a row: "))

    matrix = matrix + [[0] * column_count] * (row_index + 1 - len(matrix))

    values = [0] * (column_count + 1)
    while len(values) > column_count:
        value_string = input(f"please input up to {column_count} values for row {row_index}: ")
        values = [float(x) for x in value_string.split()]
    values = values + [0] * (column_count - len(values))
    matrix[row_index] = values

print("The resulting matrix: [")
for row in matrix:
    print(row)

print("]")

这是否有助于您了解您已经想出的部分如何协同工作?我认为这一切都应该相对容易阅读。 Python 在列表中重复元素的语法可能有点奇怪:

>>> ["hi"] * 3
['hi', 'hi', 'hi']

【讨论】:

  • 非常感谢@He3lixxx 我会将它与我所拥有的结合起来,看看它是否有效。我的意思是它应该,只是通过尝试它输出矩阵。现在我需要调整它,因为输入在同一行中并且需要具有某些条件。再次感谢您的帮助!
猜你喜欢
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多