看板 Python 關於我們 聯絡資訊
※ 引述《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
abram: 定義階乘時常用技巧 http://tinyurl.com/weljb6f 11/13 23:12
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