整数数组的基本转换

编程入门 行业动态 更新时间:2024-10-24 14:18:54
本文介绍了整数数组的基本转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写将数组中的整数转换为给定基数的代码,并对其进行填充以使它们具有相同的大小.我从 numpy.vectorize 时,Alex Martelli>"> stackoverflow 无效,尽管它适用于单个数组:

I am trying to make a code that converts integers in array to a given base and padding them to make them from the same size. The following code which I manipulated from a code on stackoverflow by Alex Martelli, doesn't work when I apply numpy.vectorize on it, although it works for single arrays:

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)

哪个终止并出现以下错误:

Which terminates with the following error:

... 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.

有没有更好的方法可以为vectors案例编写代码,而我在这里缺少什么呢?

Is there any better way to write it for vectors case, and what am I missing here.

推荐答案

以下是矢量化版本:

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 ,则该大小基于 x 中的最大值. order 确定数字的顺序;使用 order ="decreasing" (默认值)将123转换为[1、2、3].使用 order ="increasing" 获得[3,2,1].(后者可能更自然,因为结果中数字的索引与该数字的基数幂相匹配.)

If x has shape shp, the result has shape shp + (size,). If size is not given, the size is based on the largest value in x. order determines the order of the digits; use order="decreasing" (the default) to convert, say, 123 to [1, 2, 3]. Use order="increasing" to get [3, 2, 1]. (The latter might be more natural, as the index of the digit in the result matches the power of the base for that digit.)

示例:

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

更多推荐

整数数组的基本转换

本文发布于:2023-11-29 21:59:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647746.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!