numpy のitertools.combinationsを実装したいと思います。この議論に基づいて、1D入力で機能する関数があります:
def combs(a, r):
"""
Return successive r-length combinations of elements in the array a.
Should produce the same output as array(list(combinations(a, r))), but
faster.
"""
a = asarray(a)
dt = dtype([('', a.dtype)]*r)
b = fromiter(combinations(a, r), dt)
return b.view(a.dtype).reshape(-1, r)
出力は理にかなっています:
In [1]: list(combinations([1,2,3], 2))
Out[1]: [(1, 2), (1, 3), (2, 3)]
In [2]: array(list(combinations([1,2,3], 2)))
Out[2]:
array([[1, 2],
[1, 3],
[2, 3]])
In [3]: combs([1,2,3], 2)
Out[3]:
array([[1, 2],
[1, 3],
[2, 3]])
ただし、次元を追加することで、一度に複数の呼び出しをすばやく実行できるようにする ND 入力に拡張できれば最高です。したがって、概念的には、ifcombs([1, 2, 3], 2)
プロデュース[1, 2], [1, 3], [2, 3]
および combs([4, 5, 6], 2)
プロデュース は[4, 5], [4, 6], [5, 6]
、「and」が平行な行または列 (意味のある方) を表す場所combs((1,2,3) and (4,5,6), 2)
を生成する必要があります。[1, 2], [1, 3], [2, 3] and [4, 5], [4, 6], [5, 6]
(および追加の次元についても同様)
わからない:
- 他の関数が機能する方法と一貫性のある論理的な方法でディメンションを機能させる方法 (いくつかの numpy 関数が
axis=
パラメーターを持ち、軸 0 のデフォルトを持っている方法など)。他の軸は並列計算を表すだけですか?) - 上記のコードを ND で動作させる方法 (現在は
ValueError: setting an array element with a sequence.
) - もっと良い方法はあります
dt = dtype([('', a.dtype)]*r)
か?