简体   繁体   中英

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?

This should be how the code works:

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

Then the user is going to enter a value for a row followed by a value for column.

    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.

Both x and y need to follow certain conditions so I have them apart. In theory it should look something like this:

    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

Some floats are going to enter on different rows, like row 1 can have three floats from the input, and another row (row 3) could have 5 floats from the input.

I have tried using the following loop:

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

But I can't seem to be able to assign each value on the matrix as I have to make sure that the inputs follow certain conditions as the program should read as many different floats as te variable "m" goes.

The reason why I am elaborating the code this way is because I have to calculate an average (in a different function) based on the different values that I get from the float input, making them go through a formula that I already had done before.

From what I understand, this should be roughly what you need:

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

Does this help you understand how the parts you already figured out could work together? I think it should be all relatively easy to read. Python's syntax for repeating elements in a list might be a bit strange to get used to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM