包含Python中的整数列表

时间:2018-04-17 16:15:34

标签: python struct

我有一个列表,我在Python中使用struct模块打包为字节。这是我的清单:

  

[39,39,126,126,256,258,260,259,257,126]

我将我的清单打包为:

encoded = struct.pack(">{}H".format(len(list)), *list)

我将列表中的元素数作为格式传递。

现在,我需要解压缩打包的struct。为此我需要一种格式,我再次传递元素数量。现在我这样做:

struct.unpack(">{}H".format(10), encoded)

但是,我无法将其作为函数format的简单参数传递,因为该结构随后被写入我用于压缩图像的文件。如何将多个元素添加到文件中,然后将其解压缩?

P.S。我想从文件本身获取10(在解包中)作为字节打包。

2 个答案:

答案 0 :(得分:1)

从评论和问题中形成我理解的内容。也许这会有所帮助。

.Text {
  display: inline-block;
  position: absolute;
  top:50%;
  left: 50%;
  transform: translate(-50% , -50%);
  font: 200 1.25em/1.3em 'Open Sans';
  color: white;
  margin:0;
}

如果有帮助,请告诉我。

答案 1 :(得分:0)

这是我将[元素数]添加到文件中的方法:

file.write(len(compressed_list).to_bytes(3,'big'))

我为compressed_list的长度分配3个字节的内存,将其转换为字节,并将其添加到文件的开头。另外,写下其他左侧部分。

接下来,当我需要这个号码时,我会从文件中得到它:

sz = int.from_bytes(encoded[0:3],'big')

这意味着我从文件中读取字节数组的前三个字节,并将该字节强制转换为int。

这解决了我的问题。