且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用numpy将整数拆分为数字

更新时间:2022-11-14 16:08:07

非常简单:

  1. 将您的电话号码除以1,10,100,1000,...四舍五入
  2. 将结果乘以10

产生

l // 10 ** np.arange(10)[:, None] % 10

或者如果您想要一个适用的解决方案

Or if you want a solution that works for

  • 任何基地
  • 任意数量的数字和
  • 任意数量的尺寸

你可以做

l = np.random.randint(0, 1000000, size=(3, 3, 3, 3))
l.shape
# (3, 3, 3, 3)

b = 10                                                   # Base, in our case 10, for 1, 10, 100, 1000, ...
n = np.ceil(np.max(np.log(l) / np.log(b))).astype(int)   # Number of digits
d = np.arange(n)                                         # Divisor base b, b ** 2, b ** 3, ...
d.shape = d.shape + (1,) * (l.ndim)                      # Add dimensions to divisor for broadcasting
out = l // b ** d % b

out.shape
# (6, 3, 3, 3, 3)