你可以使用按位異或:
a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, a.shape)
a
# array([131, 79, 186, 90, 102, 179, 247, 28, 58, 60])
b
# array([2, 0, 2, 1, 0, 0, 2, 0, 3, 3])
a^b
# array([129, 79, 184, 91, 102, 179, 245, 28, 57, 63])
演示正確性:
a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, (1000000,) + a.shape)
# show it leaves high 6 unchanged:
print(np.all(252&a == 252&(a^b)))
# show all low 2 values equally likely:
print(np.abs(np.array([np.histogram(c, np.arange(5)-0.5, normed=True)[0] for c in ((a^b)&3).T])-0.25).max())
# True
# 0.001595
這可以很容易做足沒有NumPy的。 –