代码之家  ›  专栏  ›  技术社区  ›  Jan-Bert

使用numpy将整数拆分为数字

  •  1
  • Jan-Bert  · 技术社区  · 7 年前

    我有个问题。这个问题以前有人问过,但据我所见从来没有用过numpy。 我想把一个值分成不同的数字。做一些事情然后返回一个数字。基于下面的问题,我可以做我想做的事。 但我更喜欢在纽比做这一切。我希望它更有效,因为我不会前后更改为numpy数组。 见例子:

    例子:

    import numpy as np
    
    
    l = np.array([43365644])  # is input array
    n = int(43365644)
    m = [int(d) for d in str(n)]
    o = np.aslist(np.sort(np.asarray(m)))
    p = np.asarray(''.join(map(str,o)))
    

    我试了好几次,但运气不好。 有一次我使用了split函数,它工作了(在终端中),但是在将它添加到一个脚本中之后,它再次失败,我无法重现我以前所做的一切。

    q = np.sort(np.split(l,1),axis=1) 没有错误,但它仍然是一个单一的值。

    q = np.sort(np.split(l,8),axis=1) 使用此方法,会产生以下错误:

    Traceback (most recent call last):
    File "python", line 1, in <module>
    ValueError: array split does not result in an equal division
    

    在纽比有可能吗?提前谢谢

    参考问题:
    Turn a single number into single digits Python
    Convert list of ints to one number?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nils Werner    7 年前

    很简单:

    1. 把你的号码除以1,10,100,1000,…舍入
    2. 将结果乘以10

    其产量

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

    或者如果你想要一个有效的解决方案

    • 任何基础
    • 任意数字和
    • 任何尺寸

    你可以做到

    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)