gpt4 book ai didi

python - 整数数组的基本转换

转载 作者:行者123 更新时间:2023-11-28 22:52:42 24 4
gpt4 key购买 nike

我正在尝试制作一个代码,将数组中的整数转换为给定的基数并填充它们以使它们具有相同的大小。以下代码是我根据 stackoverflow 上的代码操作的由 Alex Martelli 编写,当我在其上应用 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.

有没有更好的方法来为向量案例编写它,我在这里遗漏了什么。

最佳答案

这是一个矢量化的版本:

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]])

关于python - 整数数组的基本转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com