首页 > 解决方案 > 拆分为字节,布尔对可变

问题描述

我正在尝试将打开的数据文件拆分为一个数组,每个单元格将包含 97 个字节的数据 + 3 个字节的单元格编号。现在我想添加一个额外的布尔变量,但这里的问题是稍后更改该布尔值,因为 python 将我的对视为一个元组。

def initialize():
    global data_arr, ack_arr, arr_size_bytes
    text = open(FILE_NAME, "rb")
    data = text.read()
    # Make new array of bytes from current file, to each segment add 3-byte long sequence number.
    data_arr = [(data[i:i + 97] + int((i / 97)).to_bytes(3, 'little')) for i in range(0, len(data), 97)]
    # Make new boolean array to hold acknowledgments received.
    ack_arr = [False for i in range(0, len(data_arr), 1)]
    text.close()

我不想创建第二个数组 ( ack_arr),而是想以某种方式创建一个可以访问data_arr[i][0/1]但也是可变的对。

标签: python

解决方案


考虑一个类架构。注意全局变量是如何消失的。

class Mydata:
    def __init__(self, filename):
        data = open(filename, "rb").read()
        # Make new array of bytes from current file, to each segment add 3-byte long sequence number.
        self.data_arr = [(data[i:i + 97] + int((i / 97)).to_bytes(3, 'little')) for i in range(0, len(data), 97)]
        # Make new boolean array to hold acknowledgments received.
        self.ack_arr = [False] * len(self.data_arr)

    def is_mutable(self,n):
        return self.ack_arr[n]

    def modify( self, index, value ):
        if not self.ack_arr[index]:
            print( "Index", index, "is not mutable")
            # Might raise an exception
        else:
            self.data_arr[index] = value

推荐阅读