2017-04-13 4 views
1

ループなしでこの結果を得る方法はありますか?私はW[range(W.shape[0]),と空想的なインデックス作成にいくつかの試みをしました...しかし、これまで失敗しています。ループなしでitertools.combinationsからnumpy配列を作成する方法

import itertools 
import numpy as np 
n = 4 
ct = 2 
one_index_tuples = list(itertools.combinations(range(n), r=ct)) 
W = np.zeros((len(one_index_tuples), n), dtype='int') 
for row_index, col_index in enumerate(one_index_tuples): 
    W[row_index, col_index] = 1 
print(W) 

結果:

[[1 1 0 0] 
[1 0 1 0] 
[1 0 0 1] 
[0 1 1 0] 
[0 1 0 1] 
[0 0 1 1]] 
+0

が重複する可能性をタプルのリストを持つ配列](http:// stackoverflow .com/questions/28491230/indexing-a-numpy-array-with-a-list-of-tuples) – maxymoo

答えて

2

次のようにあなたは空想のインデックス(advanced indexing)を使用することができます:[numpyのインデックス作成の

# reshape the row index to 2d since your column index is also 2d so that the row index and 
# column index will broadcast properly 
W[np.arange(len(one_index_tuples))[:, None], one_index_tuples] = 1 

W 
#array([[1, 1, 0, 0], 
#  [1, 0, 1, 0], 
#  [1, 0, 0, 1], 
#  [0, 1, 1, 0], 
#  [0, 1, 0, 1], 
#  [0, 0, 1, 1]]) 
0

はこれを試してみてください:

[[ 1 if i in x else 0 for i in range(n) ] for x in itertools.combinations(range(n), ct)] 
+0

これはまだループしています; – maxymoo

関連する問題