[英]An efficient way to grab the indexes for a two dimension list in python
I have this list:我有这个清单:
my_list = [[1,2,3],
[4,5,6],
[7,8,9]]
And I want the index for, let's say number nine.我想要索引,比如说九号。 It would be (2,2).
这将是(2,2)。 I want an efficient and less verbose way to get the x,y indexes and I tried this:
我想要一种有效且不那么冗长的方法来获取 x,y 索引,我尝试了这个:
def my_indexes(the_list):
(i_s, j_s) = [[(i, j) for j, cell in enumerate(row) if cell == 9] for i, row in enumerate(the_list) if 9 in row][0][0]
return (i_s, j_s)
my_indexes(my_list)
(2, 2)
It works but perhaps my approach is overcomplicated.它有效,但也许我的方法过于复杂。 Please, could you help me with a better approach?
拜托,你能帮我一个更好的方法吗? Thank you.
谢谢你。
Since this is tagged numpy, I'll give you the numpy solution由于这是标记为 numpy,我会给你 numpy 解决方案
np_list = np.array(my_list)
np.argwhere(np_list == 9)
array([[2, 2]], dtype=int64)
You can try to use this.你可以尝试使用这个。
n = 9
[(i, sub_list.index(n)) for i, sub_list in enumerate(my_list) if n in sub_list]
I got the output as [(2,2)]
for your input.我将 output 作为
[(2,2)]
供您输入。
This returns a list of tuples with indexes of all occurrences.这将返回一个元组列表,其中包含所有出现的索引。 If you need only the first occurrence you can break the iteration on the first encounter.
如果您只需要第一次出现,则可以在第一次遇到时中断迭代。 I couldn't think of a much simpler one
我想不出一个更简单的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.