Python:自动选择适当的数据类型大小(int)

mat*_*fee 5 python numpy

我正在用Python和numpy分配一个(可能很大的)零矩阵.我计划将无符号整数从1 N放入其中.

N 变化很大:很容易从1到100万,甚至更多.

我知道N在矩阵初始化之前.如何选择矩阵的数据类型,以便我知道它可以保存(无符号)大小的整数N

此外,我想选择最小的这种数据类型.

例如,如果N是1000,我会选择np.dtype('uint16').如果N是240,uint16可以工作,但uint8也可以工作,是我可以用来保存数字的最小数据类型.

这是我初始化数组的方式.我正在寻找SOMETHING_DEPENDING_ON_N:

import numpy as np
# N is known by some other calculation.
lbls = np.zeros( (10,20), dtype=np.dtype( SOMETHING_DEPENDING_ON_N ) )
Run Code Online (Sandbox Code Playgroud)

干杯!

啊哈!

刚刚实现了numpy v1.6.0 + np.min_scalar_type,文档.D'哦!(虽然答案仍然有用,因为我没有1.6.0).

wim*_*wim 4

编写一个简单的函数来完成这项工作怎么样?

import numpy as np

def type_chooser(N):
    for dtype in [np.uint8, np.uint16, np.uint32, np.uint64]:
        if N <= dtype(-1):
            return dtype
    raise Exception('{} is really big!'.format(N))
Run Code Online (Sandbox Code Playgroud)

用法示例:

>>> type_chooser(255)
<type 'numpy.uint8'>
>>> type_chooser(256)
<type 'numpy.uint16'>
>>> type_chooser(18446744073709551615)
<type 'numpy.uint64'>
>>> type_chooser(18446744073709551616)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "spam.py", line 6, in type_chooser
    raise Exception('{} is really big!'.format(N))
Exception: 18446744073709551616 is really big!
Run Code Online (Sandbox Code Playgroud)