如何在Python中将多行输入读取到二维数组中

2024-03-25

我在 python 中遇到了一个问题, 要读取的二维数组的输入格式是

3           # number of rows and columns of a square matrix
1 2 3       # first row 
3 4 6       # second row
4 6 3       # third row

如何从控制台读取二维数组,如上面所示

Python版本:3.6

IDE:Spyder(Python 3.6)


n = int(input())
matrix = dict()
for i in range(n):
    matrix["row"+str(i)] = input().split() # i assume you want the numbers seperated too

这将获取您想要的输入行数,并使用您最初所说的输入数创建一个字典

所以字典现在是矩阵

{'row0': ['1', '2', '3', '4'], 
'row1': ['3', '4', '6', '9'], 
'row2': ['4', '6', '3', '1']}

如果您希望它们存储为整数

n = int(input())
matrix = dict()
for i in range(n):
    matrix["row"+str(i)] = [int(i) for i in input().split()]

output

{'row0': [1, 2, 3, 4], 
'row1': [3, 4, 6, 9], 
'row2': [4, 6, 3, 1]}

或作为仅输出列表列表的 oneliner

[[int(i) for i in input().split()] for _ in range(int(input()))]

output

[[1, 2, 3, 4], [3, 4, 6, 9], [4, 6, 3, 1]]

或作为字典 oneliner

{'row'+str(q) : [int(i) for i in input().split()] for q in range(int(input()))}

output

{'row0': [1, 2, 3, 4], 'row1': [3, 4, 6, 9], 'row2': [4, 6, 3, 1]}

正如帕特里克指出的那样,快速的班轮可能是

{q : [int(i) for i in input().split()] for q in range(int(input()))}

output

{1: [1, 2, 3, 4], 2: [3, 4, 6, 9], 3: [4, 6, 3, 1]}

该解决方案速度更快,因为字典使用哈希,因此在到达所需索引之前不必循环遍历整个列表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中将多行输入读取到二维数组中 的相关文章

随机推荐