[英]How do I multiply a matrix by a vector in python without any built in functions where both the vector and matrix are inputs from the user
[英]Inputs from a user for matrix operations in python
这是我使用列表推导在 Python 中添加 2 个矩阵的代码:
row, col = map(int, input().split())
mat1 = [[list(map(int, input().split())) for i in range(row)] for j in range(col)]
for i in range(row):
for j in range(col):
print(mat1[i][j], end=" ")
print()
print("\n")
mat2 = [[list(map(int, input().split())) for i in range(row)] for j in range(col)]
for i in range(row):
for j in range(col):
print(mat2[i][j], end=" ")
print()
print("\n")
result = [[0 for i in range(col)] for j in range(row)]
for i in range(row):
for j in range(col):
result[i][j] = mat1[i][j] + mat2[i][j]
print("\n")
for i in range(row):
for j in range(col):
print(result[i][j], end = " ")
print()
我可以在不采用上述形式的输入的情况下运行此代码,但我在大学时遇到了编码挑战,他们以以下形式提供输入:
2 3
5 -1 3
19 8 4
4 5 -6
1 -2 12
我无法获取输入并将它们放入矩阵中。
您可以将输入流视为使用\\n
符号分行的连续字符串。 为了将 txt 文件作为输入快速传递给您的程序,您可以在 cmd 控制台/unix 终端中执行以下操作:
在 Linux/Windows 中:
python code.py < input.txt
在这里,您在code.py
有您的代码,在input.txt
文件中有您建议的输入,文件末尾带有\\n
。
您不需要使用第二个 for 循环。
mat1 = [list(map(int, input().split(' '))) for i in range(row) ]
输入
2 6 9
-1 5 10
输出
print(mat1)
[[2, 6, 9], [-1, 5, 10]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.