2017-04-13 82 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

[索引一個numpy的可能的重複具有元組列表的數組](http:// stackoverflow .com/questions/28491230/indexing-a-numpy-array-with-a-list-of-tuples) – maxymoo

回答

2

您可以使用花哨的索引(advanced indexing)如下:

# 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

相關問題