方法#1
鉴于ONLY array rows where w < x,这将是成对组合,这是实现相同的一种方法-
In [81]: r,c = np.nonzero(w[:,None]<x) # or np.less.outer(w,x)
In [82]: np.c_[w[r], x[c]]
Out[82]:
array([[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4]])
方法#2
使用纯粹的基于掩码的方法,它将是 -
In [93]: mask = np.less.outer(w,x)
In [94]: s = (len(w), len(x))
In [95]: np.c_[np.broadcast_to(w[:,None], s)[mask], np.broadcast_to(x, s)[mask]]
Out[95]:
array([[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4]])
基准测试
使用相对较大的数组:
In [8]: np.random.seed(0)
...: w = np.random.randint(0,1000,(1000))
...: x = np.random.randint(0,1000,(1000))
In [9]: %%timeit
...: r,c = np.nonzero(w[:,None]<x)
...: np.c_[w[r], x[c]]
11.3 ms ± 24.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [10]: %%timeit
...: mask = np.less.outer(w,x)
...: s = (len(w), len(x))
...: np.c_[np.broadcast_to(w[:,None], s)[mask], np.broadcast_to(x, s)[mask]]
10.5 ms ± 275 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [11]: import itertools
# @Akshay Sehgal's soln
In [12]: %timeit [i for i in itertools.product(w,x) if i[0]<i[1]]
105 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)