社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python的结构中正确填充数字

Dragos Strugar • 4 年前 • 703 次点击  

我有一个这样的元组(注意,第一个元素可以是任意大小(大但不是很大,即2**12-1可以),第二个元素总是在[0,255]范围内)。

t = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), ...]

我想将这些数字作为字节存储在文件系统中(用于压缩)。这意味着我以后还想使用这些位来恢复元组。还要注意,使用大端是必需的。

for idx, v in compressed:              
    if v:                              
        f.write(struct.pack(">I", idx))
        f.write(struct.pack(">I", v))  

但是,当我试图得到这些数字时,就像这样:

with open(filepath, 'rb') as file:          
    data = file.read(4)                     
    nums = []                               
    while data:                             
        num = struct.unpack(">I", data)[0]  
        print(num)                          
        data = file.read(4)                 
        nums.append(num)                    

我没有得到上面的数字(我支持一些数字,但后来它变得一团糟,可能是因为位填充)。

如何与位填充保持一致?我该怎么加 struct.pack('>I, ...) 我以后能可靠地得到?

更新:

对于以下元组 [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246) ...]

我用我的方法得到以下数字:

[0, 137, 0, 80, 0, 78, 0, 71, 0, 13, 0, 10, 0, 26, 9, 13, 0, 73, 0, 72, 0, 68, 0, 82, 0, 1, 0, 44, 15, 1, 17, 8, 0, 2, 0, 246 ...]

看,在(6,0)处开始发散。在那之前一切都很好。但它能自我修正吗??9点13分继续表现良好。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46354
 
703 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Massifox
Reply   •   1 楼
Massifox    4 年前

给定以下输入:

compressed = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246)]

请尝试以下代码来写入数据:

import struct

with open('file.dat', 'wb') as f:
    for idx, v in compressed:   
        f.write(struct.pack(">I", idx))
        f.write(struct.pack(">I", v)) 

下面是阅读代码:

with open('file.dat', 'rb') as f:
    data = f.read(4)                     
    nums = []
    while data:     
        idx = struct.unpack(">I", data)[0]  
        data = f.read(4)      
        v = struct.unpack(">I", data)[0]
        data = f.read(4)      
        nums.append((idx,v)) 

nums 包含:

[(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246)]

和输入一样,事实上 nums == compressed 给予 True 是的。

finefoot
Reply   •   2 楼
finefoot    4 年前

你的代码似乎运行良好。但是,您确实有以下行:

if v:

v False 对于第二个元素是 0 它不会被写入到文件中,因此在从该文件读取时也不会看到它们。