![](/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.