英文:
How to create and fill a python matrix?
问题
我试图通过使用公式来填充矩阵,但一直出现错误“list index out of range”。
你能告诉我这个错误是什么吗?
import math
n = int(input("输入行数和列数:"))
for i in range(n):
for j in range(n):
A[i][j] = (pow(10, math.log(i+1)) / pow(10, math.log(j+2))) / (math.exp(math.log10(i+1.5)) / math.exp(math.log10(j+0.5)))
for i in range(n):
for j in range(n):
print(A[i][j], end=' ')
print()
英文:
I am trying to create a matrix by filling it with a formula, but an error constantly comes out "list index out of range"
Can you please tell me what this error is?
import math
n=int(input("Enter the number of rows and columns: "))
for i in range(n):
for j in range(n):
A[i][j]=(pow(10,math.log(i+1))/pow(10,math.log(j+2)))/(math.exp(math.log10(i+1.5))/math.exp(math.log10(j+0.5)))
for i in range(n):
for j in range(n):
print(A[i][j],end=' ')
print()
答案1
得分: 1
也许这可以帮助你:
n = 3
A = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
A[i][j] = i + j
print(A)
# [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
我坚持使用in range(n)
进行初始化,因为你可能会有同时更新的列表副本,这是你不想要的:
b = [[0] * n for _ in range(n)]
b[1][0] = 2
print(b)
# [[0, 0, 0], [2, 0, 0], [0, 0, 0]]
英文:
Maybe this can help you :
n = 3
A = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
A[i][j] = i+j
print(A)
# [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
I insist on in range(n)
for initialization because you could have list copies that update at same time, which you do not want :
b = [[0]*n] * n
b[1][0] = 2
print(b)
# [[2, 0, 0], [2, 0, 0], [2, 0, 0]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论