2013-11-26 36 views
2

我想做一个代码,将数组中的整数转换为给定的基数,并填充它们使它们从相同的大小。这是我从亚历克斯·马尔泰利在stackoverflow代码操纵下面的代码,当我把它应用numpy.vectorize不起作用,然而它可以用于单一阵列:基数转换的整数数组

def int2base(x, base,size): 
    ret=np.zeros(size) 
    if x==0: return ret 
    digits = [] 
    while x: 
     digits.append(x % base) 
     x /= base 
    digits.reverse() 
    ret[size-len(digits):]=digits[:] 
    return ret 
vec_int2base=np.vectorize(int2base) 
vec_int2base(np.asarray([2,1,5]),base=3,size=3) 

与下面的错误而终止:

... 
    1640    if ufunc.nout == 1: 
    1641     _res = array(outputs, 
-> 1642        copy=False, subok=True, dtype=otypes[0]) 
    1643    else: 
    1644     _res = tuple([array(_x, copy=False, subok=True, dtype=_t) 

ValueError: setting an array element with a sequence. 

有没有更好的方法来写矢量的情况下,我在这里丢失了什么。

+0

难道我问错了问题还是什么? :) 似乎没有人有答案。 – Cupitor

回答

2

下面是被矢量版本:

import numpy as np 


def int2base(x, base, size=None, order='decreasing'): 
    x = np.asarray(x) 
    if size is None: 
     size = int(np.ceil(np.log(np.max(x))/np.log(base))) 
    if order == "decreasing": 
     powers = base ** np.arange(size - 1, -1, -1) 
    else: 
     powers = base ** np.arange(size) 
    digits = (x.reshape(x.shape + (1,)) // powers) % base 
    return digits 

如果x已经塑造shp,其结果具有形状shp + (size,)。 如果没有给出size,则尺寸基于x中的最大值。 order确定数字的顺序;使用order="decreasing"(默认值)将123转换为[1,2,3]。使用order="increasing"获得[3,2,1]。 (后者可能是更自然,在结果数字的指数的基础是数字的功率相匹配。)

例子:

In [97]: int2base([255, 987654321], 10) 
Out[97]: 
array([[0, 0, 0, 0, 0, 0, 2, 5, 5], 
     [9, 8, 7, 6, 5, 4, 3, 2, 1]]) 

In [98]: int2base([255, 987654321], 10, size=12) 
Out[98]: 
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 5], 
     [0, 0, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1]]) 

In [99]: int2base([255, 987654321], 10, order="increasing") 
Out[99]: 
array([[5, 5, 2, 0, 0, 0, 0, 0, 0], 
     [1, 2, 3, 4, 5, 6, 7, 8, 9]]) 

In [100]: int2base([255, 987654321], 16) 
Out[100]: 
array([[ 0, 0, 0, 0, 0, 0, 15, 15], 
     [ 3, 10, 13, 14, 6, 8, 11, 1]]) 
2

我在汇编程序中使用“fromBase10”函数(下面)时有相当的数量。请注意,它不会填充输出,但numpy.vectorize确实可以使用它。只是不要忘记垫。

## Execute this to convert a base 10 into any arbitrary base 
def fromBase10(number, base): 
    if not number: 
     return '0' 
    sign = 1 if number > 0 else -1 
    alphanum = string.digits + string.ascii_lowercase 
    nums = alphanum[:base] 
    res = '' 
    number *= sign 

    while number: 
     number, mod = divmod(number, base) 
     res += nums[mod] 
    return ('' if sign == 1 else '-') + res[::-1] 

请注意,我从Stack Exchange上的其他人复制了基本例程,但我不再记得在哪里。我只是不想邀功的地方是不是我:)

+0

我的代码返回的不是一个字符串的向量。如果我改变这个,恐怕这个代码会面临同样的问题。我不是基于字母的转换,而是“基本转换”的数学定义。不管怎样,谢谢。 – Cupitor

+1

'i2b = lambda x,b,s:i2b(x // b,b,s-1)+ str(x%b)if x else“0”* max(s,0)'... but it仍然是一个字符串:P –

+0

@JoranBeasley,谢谢,但没有帮助:D – Cupitor