如何在没有循环的情况下从itertools.combinations创建一个numpy数组
问题描述:
有没有办法让这个结果没有循环?我在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]]
答
您可以使用花哨的索引(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]])
答
试试这个:
[[ 1 if i in x else 0 for i in range(n) ] for x in itertools.combinations(range(n), ct)]
+0
这仍然是循环寿命;) – maxymoo
[索引一个numpy的可能的重复具有元组列表的数组](http:// stackoverflow .com/questions/28491230/indexing-a-numpy-array-with-a-list-of-tuples) – maxymoo