擅长:python、mysql、java
<p>对于1d数组,可以使用这种一种线性数乘方法,使用<code>np.packbits</code>:</p>
<pre><code>>>> np.packbits(np.pad((s0+1).astype(bool).astype(int), (8-s0.size, 0), 'constant'))
array([11], dtype=uint8)
</code></pre>
<p>对于倒车:</p>
^{pr2}$
<p>对于二维阵列:</p>
<pre><code>>>> x, y = s.shape
>>> np.packbits(np.pad((s+1).astype(bool).astype(int), (8-y, 0), 'constant')[-2:])
array([5, 7], dtype=uint8)
</code></pre>
<p>对于倒车:</p>
<pre><code>>>> unpack = (np.unpackbits(np.array([5, 7], dtype='uint8'))).astype(float).reshape(x, 8)[:,-y:]
>>> unpack[unpack==0] = -1
>>> unpack
array([[ 1., -1., 1.],
[ 1., 1., 1.]])
</code></pre>