Python 2.7 连续数对角矩阵

Python 2.7 连续数对角矩阵,python-2.7,matrix,canopy,Python 2.7,Matrix,Canopy,我想在下面创建一个对角矩阵,这是python 2.7中的代码 def diag(steps): ''' steps : a positive integer ''' matrix = [[0]*steps]*steps # matrix of the order step x step for i in range(steps + 1): matrix[i][i] = i + 1 # i'th' element of 'i'th

我想在下面创建一个对角矩阵,这是python 2.7中的代码

def diag(steps):
    '''
    steps : a positive integer
    '''
    matrix = [[0]*steps]*steps    # matrix of the order step x step
    for i in range(steps + 1):
        matrix[i][i] = i + 1    # i'th' element of 'i'th row
    return matrix
对于例如:如果步骤=3,我应该得到[[1,0,0],[0,2,0],[0,0,3]]。 但是我得到了[[1,2,3],[1,2,3],[1,2,3]] 有没有人能帮我解决这个问题,请告诉我我的逻辑有什么问题?< /P> < P > 1。为了方便起见,你可以考虑使用<代码> NoMPy < /Cord>,它允许以更“数学”的方式工作,而不是Python的列表。 在您的例子中,您可能想看看
numpy.diag(vector)
,它创建了
len(vector)xlen(vector)
矩阵,其中
matrix[i][i]=vector[i]

根据您的需要,使用numpy您可以执行以下操作:

import numpy as np
matrix = np.diag( list(range(1, steps+1))
就这些

2) 要回答您的确切问题(以防您因某种原因无法使用numpy),您可以将其缩短:

def diag(steps):
    matrix = [ [0]*i+[i+1]+[0]*(steps-i-1) for i in range(steps) ]
    return matrix

通过乘以一个数组,您不会创建包含三个不同数组的矩阵。可以创建对同一数组的多个引用

例如:

> a = [2,2,2]
> b = [a]*3
> print b
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
> a[1] = 4
> print b
[[2, 4, 2], [2, 4, 2], [2, 4, 2]]
> b[0][0] = 8
> print b 
[[8, 4, 2], [8, 4, 2], [8, 4, 2]]
看到了吗?现在每个3-数组中的第一个元素都是8,而不仅仅是b[0][0]。这是因为它们都是同一个对象

你必须改变

matrix = [[0]*steps]*steps 


当然,在我赢得15个声誉之后,我最终会的。在那之前我不能投票。SorryVerification这个问题对于下一个来到这里的用户来说更为重要:)您应该验证一个anwser的可能重复项
# probably not the best pythonic way but it works
matrix = [[0 for x in range(steps)] for x in range(steps)]