作者flarehunter (Range)
看板Python
標題Re: [問題] 在任意維度的 List 中找某元素的位置?
時間Wed Nov 13 20:33:34 2019
※ 引述《abram (科科)》之銘言:
: 不好意思,因為用習慣了 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 下實作類似的功能呢?
: 謝謝!
如果是List的話就遞迴下去找,找到最後如果符合的話就回傳index
def Find(arr, value, current_idx):
if not isinstance(arr, list):
if arr == value:
return [current_idx]
else:
return []
ret = []
for idx, item in enumerate(arr):
ret += Find(item, value, current_idx + [idx])
return ret
arr = [2, [1, 2], [[1, 1, 2]]]
print Find(arr, 2, []) # [[0], [1, 1], [2, 0, 2]]
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 126.74.152.122 (日本)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1573648416.A.B01.html
推 abram: 太強了 謝謝 學到一課! 11/13 21:04
推 abram: 這樣就能處理任何維度矩形和非矩形的list了 讚 11/13 21:11
推 abram: 沒想到可以在Find的定義裡面使用Find 太黯然太銷魂了 11/13 21:13
推 Ryspon: 推 11/13 22:29
推 disney82231: 有點不太懂為什麼可以在Find裡面使用Find,有大大可 11/13 22:56
→ disney82231: 以解釋嗎 11/13 22:56
推 abram: 回樓上 函式用自我呼叫的方式完成遞迴 11/13 23:11
推 bdx915: To iterate is human ,To recurse is divine 11/14 09:09
推 bookstar07: 這篇回文讓我學到好多小技巧... 11/15 23:38
→ bookstar07: 原本以為小懂python 結果發現新大陸XD 11/15 23:38
推 a110482: 可以查關鍵字"recursive" 12/08 16:39