编写一个函数以python中的数组形式返回数组的对角线元素(NxN)

时间:2018-11-26 09:10:40

标签: python numpy

import numpy as np
#getting number of rows and columns for the arrat
nr=input("enter rows")
nc=input("enter columns")
print("Please enter same rows and columns")
n=nr*nc
ar1=[]
#checking for square matrix
if(nr==nc):
#loop to append elements into the empty-list ar1
  for i in range(n):
     ele=input("enter elements")
     ar1.append(ele)
#getting the number of rows of array1
array1=np.array(ar1).shape
#function to get the diagonal elements of array
def diagonal(a):
  global n
  n=str(n)
  for i in n:
     for j in n:
       if i==j:

          newarr=np.array(a[i][j])

  #print(newarr) 
diagonal(array1)

newarr = np.array(a [i] [j])导致显示以下错误:    #TypeError:元组索引必须是整数,而不是下面代码的str

2 个答案:

答案 0 :(得分:0)

如果您知道矩阵将是正方形,则无需分别输入行和列。您可以只取值n。对角线函数将如下所示:

newa=[]
def diag(arr):
    for i,a in enumerate(arr):
        newa[i]=arr[i,i]

答案 1 :(得分:0)

我确实同意@Gautam,顺便说一下,这是一个使用内置diagonal函数的解决方法:

lst = []
size = int(input('Enter size of sqaure matrix'))
for i in range(1, (size**2)+1):
    lst.append(int(input('Enter ' + str(i) +'th element')))
lst

Enter size of sqaure matrix2
Enter 1th element5
Enter 2th element6
Enter 3th element8
Enter 4th element7
[5, 6, 8, 7]

arr = np.array(lst).reshape(size,size)
arr.diagonal()

[5, 7]