[問題] 在任意維度的 List 中找某元素的位置?

作者: abram (科科)   2019-11-13 19:18:29
不好意思,因為用習慣了 Mathematica 的 Position 指令,
所以小弟正在用 Python 寫一個執行相同功能的指令。
現在卡住的點是,如果知道輸入的 List 是二維的,
當然就是用兩層的 for loop:
def position(arr,cri):
index=[];
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == cri:
index.append([i, j])
return index
相對地,若知道輸入 List 是三維的當然就用三層的 loop。
可是當程式處理的維度由輸入 List 內生決定時,例如在
Mathematica 可以執行:
Position[{2, {1, 2}, {{1, 1, 2}}}, 2]
得到結果為:
{{1}, {2, 2}, {3, 1, 3}}
不知道要怎麼寫才能在 Python 下實作類似的功能呢?
謝謝!
作者: s860134 (s860134)   2019-11-13 19:42:00
itertools 弄成一維
作者: abram (科科)   2019-11-13 19:52:00
弄成一維只能知道是否含此元素 無法知道位置
作者: s860134 (s860134)   2019-11-13 20:04:00
要找index 那用遞迴呼叫就可以了 看要 bfs 還dfs
作者: TitanEric (泰坦)   2019-11-13 20:09:00
可以用numpy搭配where
作者: abram (科科)   2019-11-13 20:51:00
謝謝 argwhere對於任意維度的長方矩陣確實有用雖然對於非矩形的不對稱list不適用 但也夠用了
作者: nevak (^o^)   2019-11-13 21:06:00
可以用type()來判斷是不是listex: https://gitlab.com/snippets/1912813 也可以用recursive更簡潔一點

Links booklink

Contact Us: admin [ a t ] ucptt.com