简体   繁体   中英

How to get the index of specific item in python matrix

I am newbie to Python programming language. And I am looking for How to get the indexes (line and column ) of specific element in matrix.

In other I way I want to do the same as this source code using lists.

myList=[1,10,54,85]
myList.index(54)

Best Regards

Here's a simple function which returns the coordinates as a tuple (or None if no index is found). Note that this is for 2D matrices, and returns the first instance of the element in the matrix.

(Edit: see hiro protagonist's answer for an alternative Pythonic version)

def find(element, matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == element:
                return (i, j)

Or, if you want to find all indexes rather than just the first:

def findall(element, matrix):
    result = []
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j] == element:
                result.append((i, j))
    return result

You can use it like so:

A = [[5, 10],
     [15, 20],
     [25, 5]]


find(25, A) # Will return (2, 0)
find(50, A) # Will return None

findall(5, A) # Will return [(0, 0), (2, 1)]
findall(4, A) # Will return []

a (in my opinion) more pythonic version of FlipTack's algorithm :

def find(element, matrix):
    for i, matrix_i in enumerate(matrix):
        for j, value in enumerate(matrix_i):
            if value == element:
                return (i, j)

in python it is often more natural to iterate over elements of lists instead of just the indices; if indices are needed as well, enumerate helps. this is also more efficient.

note: just as list.index (without a second argument) this will only find the first occurrence.

Since you say that you're a beginner, pardon me if you already know some of the below. Just in case I'll describe the basic logic you can use to write your own function or understand the other answers posted here better: To access an element in a specific row of a list, for example, if you wanted to get the first element and save it in a variable:

myList=[1,10,54,85]
myvar = myList[0] # note that you access the first element with index 0

myvar now stores 1. Why index 0? Think of the index as an indicator of "how far away from the beginning of the list an element is." In other words, the first element is a distance of 0 from the start. What if you have a multi-dimensional list like so?

multi = [[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]
        ]

Now you think in terms of row and column (and of course you could have n-dimensional lists and keep going).

How to retrieve the 5? That is a distance of 1 row from the start of the list of rows and 2 columns away from the start of the sub-list. Then:

myvar = multi[1][2]

retrieves the 5.

FlipTack's and hiro protagonist's functions wrap this logic in the nice compact procedures, which search the entire 2-dimensional list, comparing elements until the desired one is found, then returning a tuple of the indices or continuing to search for duplicate elements. Note that if your lists are guaranteed to sorted you can then use a binary search algorithm across rows and columns and get the answer faster, but no need to worry about that for now. Hopefully this helps.

You can also add a tag to your function to search the occurrences of your input matrix/list.

For example:

If you input is 1D vector:

def get_index_1d(a = [], val = 0, occurrence_pos = False):
    if not occurrence_pos:
        for k in range(len(a)):
            if a[k] == val:
                return k
    else:
        return [k for k in range(len(a)) if a[k] == val]

Output:

a = [1,10,54,85, 10]
index = get_index_1d(a, 10, False)
print("Without occurrence: ", index)
index = get_index_1d(a, 10, True)
print("With occurrence: ", index)

>>> Without occurrence:  1
>>> With occurrence:  [1, 4]

For 2D vector:

def get_index_2d(a = [], val = 0, occurrence_pos = False):
    if not occurrence_pos:
        for k in range(len(a)):
            for j in range(len(a[k])):
                if a[k][j] == val:
                    return (k, j)

    else:
        return [(k, j) for k in range(len(a)) for j in range(len(a[k])) if a[k][j] == val]

Output:

b = [[1,2],[3,4],[5,6], [3,7]]
index = get_index_2d(b, 3, False)
print("Without occurrence: ", index)
index = get_index_2d(b, 3, True)
print("With occurrence: ", index)

>>> Without occurrence:  (1, 0)
>>> With occurrence:  [(1, 0), (3, 0)]

Just wanted to throw another solution since I didn't see it above:

def find(matrix, value):
    value_indexs = [ ( matrix.index(row), row.index(value) ) for row in matrix if value in row]
    return value_indexs

Example:

matrix = [
    [0, 1, 2],
    [3, 4, 5, 6],
    [7, 8, 9, 0]
]
find(matrix, 0) 

Returns: [(0,0), (2,3)]

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