在二维矩阵中查找值的索引
问题描述:
我有一个形式的矩阵,
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.