如何创建和填充一个Python矩阵?

huangapple go评论64阅读模式
英文:

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]]

huangapple
  • 本文由 发表于 2023年2月23日 23:43:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定