如何根据从输入接收到的行数和列数构建Python矩阵(多维数组)

问题描述 投票:0回答:2

给定具有整数元素的矩形数组(矩阵)MxN。 M 和 N 是矩形矩阵的行数和列数,从以规格分隔的一行中的输入接收。接下来,N 行,每行 M 个数字,用空格分隔 - 矩阵的元素,整数,绝对值不超过 100。

例如:

示例输入:

2 3
1 -2 3
4 5 6

示例输出:

[[1, -2, 3], [4, 5, 6]]

代码:

cols, rows = [int(i) for i in input().split(" ")] 

l = [[list(map(int, input()))] for j in range(rows)]

行很清楚,但是,我不知道如何控制行长度,因此它等于从输入接收的数字作为列

任何提示将不胜感激...

python arrays python-3.x matrix input
2个回答
1
投票

首先根据示例输出,我看到行和列应该互换,然后使用按列[:cols]分割,如下面的代码所示

rows, cols = [int(i) for i in input().split(" ")]
l = [map(int, input().split(" ")[:cols]) for i in range(rows)]

0
投票

你可以尝试使用 loop 获取输入,并在 python3 中收到空字符串时中断它。

lis = []
val = [map(int, input().split(" ")]
lis.append(val)
while val != "":
    val = [map(int, input().split(" ")]
    lis.append(val)

你就有了。没有预定义行和列的矩阵。

© www.soinside.com 2019 - 2024. All rights reserved.