![](/img/trans.png)
[英]Most efficient way to find the indexes of unique values in a Python 3 list
[英]An efficient way to grab the indexes for a two dimension list in python
我有这个清单:
my_list = [[1,2,3],
[4,5,6],
[7,8,9]]
我想要索引,比如说九号。 这将是(2,2)。 我想要一种有效且不那么冗长的方法来获取 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)
它有效,但也许我的方法过于复杂。 拜托,你能帮我一个更好的方法吗? 谢谢你。
由于这是标记为 numpy,我会给你 numpy 解决方案
np_list = np.array(my_list)
np.argwhere(np_list == 9)
array([[2, 2]], dtype=int64)
你可以尝试使用这个。
n = 9
[(i, sub_list.index(n)) for i, sub_list in enumerate(my_list) if n in sub_list]
我将 output 作为[(2,2)]
供您输入。
这将返回一个元组列表,其中包含所有出现的索引。 如果您只需要第一次出现,则可以在第一次遇到时中断迭代。 我想不出一个更简单的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.