python - 拆分为字节,布尔对可变
问题描述
我正在尝试将打开的数据文件拆分为一个数组,每个单元格将包含 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]
但也是可变的对。
解决方案
考虑一个类架构。注意全局变量是如何消失的。
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
推荐阅读
- node.js - 无法使用 Node.js 和 React Native 将文件上传到服务器
- html - 本地背景图片不显示,但如果我用网络上的一张替换它,它确实有效
- typescript - 打字稿单元测试私有和受保护方法
- react-native - 使用 React Native 的 WebView 获取 JSON 的正确方法
- python - Django:如何在模板中显示模型字段的总和
- spring - 春季安全。主体=匿名用户,类型=AUTHORIZATION_FAILURE
- user-experience - 为什么你不应该阻止右键单击网站
- reactjs - .env 显示不正确的值
- c - valgrind 显示内存泄漏。我如何阻止泄漏?
- xcode - 在 Xcode 中使用 AppleScript App 读取文本文件