看板 Python 關於我們 聯絡資訊
不好意思,因為用習慣了 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 下實作類似的功能呢? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.169.100.216 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1573643911.A.4C0.html
s860134: itertools 弄成一維 11/13 19:42
abram: 弄成一維只能知道是否含此元素 無法知道位置 11/13 19:52
s860134: 要找index 那用遞迴呼叫就可以了 看要 bfs 還dfs 11/13 20:04
TitanEric: 可以用numpy搭配where 11/13 20:09
abram: 謝謝 argwhere對於任意維度的長方矩陣確實有用 11/13 20:51
abram: 雖然對於非矩形的不對稱list不適用 但也夠用了 11/13 20:52
nevak: 可以用type()來判斷是不是list 11/13 21:06
nevak: ex: https://gitlab.com/snippets/1912813 也可以用recurs 11/13 21:07
nevak: ive更簡潔一點 11/13 21:07