前提・実現したいこと
リストgridの要素としてnumpyのnumpy.meshgridの返り値を代入しているのですが、dimensionの値によって、引数の数と返り値の数を変更するようにしたいです。
現状ではif文で分岐させていますが、見づらいのとdimension == 100等の場合、対応が難しいです。
該当のソースコード
Python3
1axis_grid = [] 2for i in range(5): 3 axis_grid.append(np.linspace(-15, 15, 10)) 4 5dimension = len(axis_grid) 6 7grid = [] 8for i in range(dimension): 9 grid.append([]) 10if dimension == 2: 11 grid[0], grid[1] = np.meshgrid(axis_grid[0], axis_grid[1]) 12elif dimension == 3: 13 grid[0], grid[1], grid[2] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2]) 14elif dimension == 4: 15 grid[0], grid[1], grid[2], grid[3] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3]) 16elif dimension == 5: 17 grid[0], grid[1], grid[2], grid[3], grid[4] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4]) 18elif dimension == 6: 19 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5]) 20elif dimension == 7: 21 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6]) 22elif dimension == 8: 23 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6], axis_grid[7]) 24elif dimension == 9: 25 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6], axis_grid[7], axis_grid[8]) 26elif dimension == 10: 27 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8], grid[9] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6], axis_grid[7], axis_grid[8], axis_grid[9]) 28elif dimension == 11: 29 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8], grid[9], grid[10] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6], axis_grid[7], axis_grid[8], axis_grid[9], axis_grid[10]) 30elif dimension == 12: 31 grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8], grid[9], grid[10], grid[11] = np.meshgrid(axis_grid[0], axis_grid[1], axis_grid[2], axis_grid[3], axis_grid[4], axis_grid[5], axis_grid[6], axis_grid[7], axis_grid[8], axis_grid[9], axis_grid[10], axis_grid[11])
回答というわけではないのですがぱっと検索してみたら
https://www.it-swarm-ja.tech/ja/python/3d%e3%81%aenumpy-meshgrid/968575565/
こちらのmeshgrid2を使うことで可変長引数にして、meshgrid2(axis_grid) と呼び出すことができるように見えました。どうかな...