简体   繁体   English

如何获取python矩阵中特定项目的索引

[英]How to get the index of specific item in python matrix

I am newbie to Python programming language.我是 Python 编程语言的新手。 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).这是一个简单的函数,它以元组的形式返回坐标(如果没有找到索引,则返回None )。 Note that this is for 2D matrices, and returns the first instance of the element in the matrix.请注意,这适用于 2D 矩阵,并返回矩阵中元素的第一个实例。

(Edit: see hiro protagonist's answer for an alternative Pythonic version) (编辑:请参阅hiro 主角的替代 Pythonic 版本的答案

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 :一个(在我看来)更 Python 版本的FlipTack 算法

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;在 python 中,迭代列表的元素而不仅仅是索引通常更自然; if indices are needed as well, enumerate helps.如果还需要索引,请enumerate帮助。 this is also more efficient.这也更有效率。

note: just as list.index (without a second argument) this will only find the first occurrence.注意:就像list.index (没有第二个参数),这只会找到第一次出现。

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? myvar 现在存储 1。为什么索引 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.换句话说,第一个元素与起点的距离为 0。 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).现在你从行和列的角度来思考(当然你可以有 n 维列表并继续前进)。

How to retrieve the 5?如何找回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.即距行列表开头 1 行,距子列表开头 2 列。 Then:然后:

myvar = multi[1][2]

retrieves the 5.检索 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. FlipTack 和 hiro protagonist 的函数将此逻辑包装在漂亮的紧凑过程中,它们搜索整个二维列表,比较元素直到找到所需的元素,然后返回索引元组或继续搜索重复元素。 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)]返回:[(0,0), (2,3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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