Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获得矩阵中对角线元素的索引?_Python_List_Matrix_Indexing_Grid - Fatal编程技术网

Python 如何获得矩阵中对角线元素的索引?

Python 如何获得矩阵中对角线元素的索引?,python,list,matrix,indexing,grid,Python,List,Matrix,Indexing,Grid,为了进一步解释,我将举一个例子。我有一个由随机数组成的8x8网格 m = [ [1 ,5, 2, 8, 6, 9, 6, 8] [2, 2, 2, 2, 8, 2, 2, 1] [9, 5, 9, 6, 8, 2, 7, 2] [2, 8, 8 ,6 ,4 ,1 ,8 ,1] [2, 5, 5, 5, 4, 4, 7, 9] [3, 9, 8, 8, 9, 4, 1, 1] [8, 9, 2, 4, 2, 8, 4, 3] [4, 4, 7, 8, 7, 5, 3, 6]] 我已经编写了代码,

为了进一步解释,我将举一个例子。我有一个由随机数组成的8x8网格

m = [
[1 ,5, 2, 8, 6, 9, 6, 8]
[2, 2, 2, 2, 8, 2, 2, 1]
[9, 5, 9, 6, 8, 2, 7, 2]
[2, 8, 8 ,6 ,4 ,1 ,8 ,1]
[2, 5, 5, 5, 4, 4, 7, 9]
[3, 9, 8, 8, 9, 4, 1, 1]
[8, 9, 2, 4, 2, 8, 4, 3]
[4, 4, 7, 8, 7, 5, 3, 6]]
我已经编写了代码,给出了给定x和y值的对角线列表。例如,如果x为2,y为3,则返回对角线
[2,5,8,5,9,8,3]
。代码如下:

def main():
    m = [[1 ,5, 2, 8, 6, 9, 6, 8],[2, 2, 2, 2, 8, 2, 2, 1],[9, 5, 9, 6, 8, 2, 7, 2],[2, 8, 8 ,6 ,4 ,1 ,8 ,1],[2, 5, 5, 5, 4, 4, 7, 9],[3, 9, 8, 8, 9, 4, 1, 1],[8, 9, 2, 4, 2, 8, 4, 3],[4, 4, 7, 8, 7, 5, 3, 6]]
    x = 2
    y = 3
    for i in m:
        print(i)
    print(diagonal(m,x,y))


def diagonal(m, x, y):
    #x
    row = max((y - x, 0))
    #y
    col = max((x - y, 0))
    while row < len(m) and col < len(m[row]):
        yield m[row][col]
        row += 1
        col += 1
main()
def main():
m=[[1,5,2,8,6,9,6,8],[2,2,2,8,2,2,2,1],[9,5,9,6,8,2,7,2],[2,8,8,6,4,1,8,1],[2,5,5,5,4,7,9],[3,9,8,8,9,4,4,2,8,4,3],[4,4,7,5,3,6]]
x=2
y=3
对于我在m:
印刷品(一)
打印(对角线(m,x,y))
def对角线(m、x、y):
#x
行=最大值(y-x,0))
#y
col=最大值((x-y,0))
而行

我的问题是,如何获得对角线列表中给定元素的索引。在本例中,坐标是
x=2
y=3
(即数字8),结果对角线是
[2,5,8,5,9,8,3]
,因此元素的索引是2。此外,我不能使用numpy供参考

您可以使用
list.index(element)
获取列表中元素的索引。 例如:

diagonal = [2,5,8,5,9,8,3]
theIndex = diagonal.index(8)
print(theIndex)
我希望这有帮助。祝你好运

首先,x
if x<y:
   row = y-x
   idx = y-row

我建议您更改函数(或创建一个变量)以返回带有坐标和数字的元组,而不仅仅是数字(类似于enumerate()所做的操作)。将其映射到数字并在之后查找数字的坐标会更容易

换句话说,如果您:

yield (row,col,m[row][col])
您可以通过以下方式仅获取数字:

numbers = [ num for row,col,num in diagonal(m,2,3) ]

但是你也可以在需要的时候操纵坐标

哇!我没想到会这么简单,谢谢
numbers = [ num for row,col,num in diagonal(m,2,3) ]