【问题标题】:How to create a numpy array from itertools.combinations without looping如何从 itertools.combinations 创建一个 numpy 数组而不循环
【发布时间】:2017-09-08 23:33:12
【问题描述】:

有没有办法在没有循环的情况下得到这个结果?我曾多次尝试使用 W[range(W.shape[0]),... 进行花式索引,但到目前为止都没有成功。

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]]

【问题讨论】:

标签: python numpy indexing


【解决方案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]])

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 这仍在循环中;)
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2019-08-28
    相关资源
    最近更新 更多