[英]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.