在二维矩阵中查找值的索引 [英] Find indices of a value in 2d matrix

查看:127
本文介绍了在二维矩阵中查找值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形式的矩阵,

mymatrix=[[1,2,3],[4,5,6],[7,8,9]]

我想获取例如位于(2,2)处的9的索引.

I want to the get the index of, say for example, 9 which is at (2,2).

到目前为止我一直在尝试做的事情.

What I have tried to do so far.

for i,j in enumerate(mymatrix):
   for k,l in enumerate(j):
     if l==9:
         print i,k

有没有更好的方法可以做到这一点.优化,有人吗?预先感谢.

Is there a better way of doing the same. Optimization, anyone? Thanks in advance.

推荐答案

如果希望该值出现的所有位置,则可以使用以下列表推导,将val设置为要搜索的内容

If you want all of the locations that the value appears at, you can use the following list comprehension with val set to whatever you're searching for

[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]

例如:

>>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
>>> val = 9
>>> [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
[(0, 2), (1, 1), (2, 2)]

编辑

这并不是真的,因为它只会出现所有出现的值,只会在给定的行中第一次出现该值.

It's not really true that this gets all occurrences, it will only get the first occurrence of the value in a given row.

这篇关于在二维矩阵中查找值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆