gpt4 book ai didi

python - 将 python 长整数放入内存,它们之间没有任何空格

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:44 24 4
gpt4 key购买 nike

我想将许多大的长整数放入内存,它们之间没有任何空格。如何在 Linux 中使用 Python 2.7 代码做到这一点?

大长整数都使用相同的位数。总共有大约 4 GB 的数据。留出几位的空间以使每个长整数在内存中使用 8 位的倍数是可以的。稍后我想对它们进行按位运算。

到目前为止,我使用的是 python 列表。但我不确定这是否会在整数之间留下内存空间。 ctypes 有帮助吗?

谢谢。

旧代码使用位数组 ( https://pypi.python.org/pypi/bitarray/0.8.1 )

import bitarray
data = bitarray.bitarray()
with open('data.bin', 'rb') as f:
data.fromfile(f)
result = data[:750000] & data[750000:750000*2]

这有效,位数组在内存中没有间隙。但是,bitarray bitwise and 在计算机上比原生python对long integer的bitwise operation慢了大约6倍。在旧代码中对位数组进行切片和在新代码中访问列表中的元素所用的时间大致相同。

较新的代码:

import cPickle as pickle

with open('data.pickle', 'rb') as f:
data = pickle.load(f)
# data is a list of python's (long) integers
result = data[0] & data[1]

NumPy 的:在上面的代码中。 result = data[0] & data[1] 创建一个新的长整数。Numpy 有 numpy.bitwise_and 的输出选项。这将避免创建一个新的 numpy 数组。然而,numpy 的 bool 数组似乎每个 bool 使用一个字节而不是每个 bool 使用一位。虽然将 bool 数组转换为 numpy.uint8 数组可以避免这个问题,但计算设置位的数量太慢了。

python 的原生数组不能处理大的长整数:

import array
xstr = ''
for i in xrange(750000):
xstr += '1'
x = int(xstr, 2)

ar = array.array('l',[x,x,x])
# OverflowError: Python int too large to convert to C long

最佳答案

您可以使用 array模块,例如:

import array
ar = array('l', [25L, 26L, 27L])
ar[1] # 26L

关于python - 将 python 长整数放入内存,它们之间没有任何空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090080/

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