﻿ python – 使用所有可能列创建二维数组的优雅方法 - 代码日志

#### python – 使用所有可能列创建二维数组的优雅方法

``````[0,0,0,0,0],  [0,0,0,0,1], [0,0,0,1,0], [0,0,0,1,1], [0,0,1,0,0], ...
``````

`````` np.array(list(itertools.product([0,1],repeat = c))).T
``````

``````(((np.arange(2**r)[:,None] & 2**np.arange(r)[::-1]))>0).astype(int)
``````

``````np.unpackbits(np.arange(2**r,dtype='uint8')[:,None], axis=1)[:,8-r:]
``````

``````In [217]: r = 5

In [218]: from itertools import product

In [219]: %timeit np.array(list(product([0,1], repeat=5)))
10000 loops, best of 3: 33.9 µs per loop

In [220]: %timeit np.unpackbits(np.arange(2**r,dtype='uint8')[:,None], axis=1)[:,8-r:]
100000 loops, best of 3: 10.6 µs per loop

In [221]: %timeit (((np.arange(2**r)[:,None] & 2**np.arange(r)[::-1]))>0).astype(int)
10000 loops, best of 3: 31.1 µs per loop
``````

``````In [242]: r = 15

In [243]: %timeit (((np.arange(2**r)[:,None] & 2**np.arange(r)[::-1]))>0).astype(int)
100 loops, best of 3: 6.6 ms per loop

In [244]: %timeit np.array(list(product([0,1], repeat=r)))
10 loops, best of 3: 77.5 ms per loop
``````