def new_matrix():
Rows=int(input("enter number of rows:"))
columns=int(input("enter number of columns:"))
matrix=[[0]*Rows for _ in range(columns)]
print (matrix)
for k in range (columns):
for p in range(Rows):
matrix[k][p]=int(input("Enter elements in matrix:"))
print (matrix)
new_matrix()
輸出爲方陣錯誤:此代碼工作好方陣,但顯示其它的矩陣
enter number of rows:2
enter number of columns:2
[[0, 0], [0, 0]]
Enter elements in matrix:1
Enter elements in matrix:2
Enter elements in matrix:3
Enter elements in matrix:4
[[1, 2], [3, 4]]
錯誤非方陣:
enter number of rows:1
enter number of columns:4
[[0], [0], [0], [0]]
Enter elements in matrix:1
Enter elements in matrix:2
Traceback (most recent call last):
File "C:/Users/kcgov/PycharmProjects/making_matrix/creating_a_matrix.py", line 10, in <module>
new_matrix()
File "C:/Users/kcgov/PycharmProjects/making_matrix/creating_a_matrix.py", line 8, in new_matrix
matrix[k][p]=int(input("Enter elements in matrix:"))
IndexError: list assignment index out of range
我無法重現你的錯誤。這個對我有用。 – DyZ
我也沒有遇到任何錯誤,但很顯然,您已顛倒了「行」和「列」的標準含義。 –
@MrGeek哎呀... – DyZ