2017-04-13 1 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-of-a-a-list-of-tuples) – maxymoo

답변

2

당신은 멋진 색인 (advanced indexing)를 사용하여 다음과 같이 [A 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

관련 문제