简体   繁体   中英

How can I get the index of an element of a diagonal in a matrix?

To explain further, I will give an example. I have a 8x8 grid made up of random numbers,

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

I have written code that gives me the list of the diagonal given an x and y value. For example, if an x of 2 and ay of 3 is given, the diagonal [2,5,8,5,9,8,3] will be returned. This is the code:

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()

My question is, how could I get the index of the given element in the diagonal list. In the example, the coordinates are x=2 and y=3 (which is the number 8), and the resulting diagonal is [2,5,8,5,9,8,3] , so the index of the element is 2. Also I cannot use numpy fyi.

You can grab the index of a element in a list by using list.index(element) . For example:

diagonal = [2,5,8,5,9,8,3]
theIndex = diagonal.index(8)
print(theIndex)

I hope this helps. Good luck!

First, the case where x

if x<y:
   row = y-x
   idx = y-row

This simplifies to idx=x, and by symetry

idx = min(x,y)

I would suggest you change your function (or make a variant) to return a tuple with the coordinates and numbers instead of just the numbers (similar to what enumerate() does. It will be easier to map this to numbers and find coordinates of numbers afterward

In other words, if you:

yield (row,col,m[row][col])

you will be able to obtain just the numbers with :

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

but you will also be able to manipulate the coordinates when you need to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM