如何将解压缩的值从二进制数据文件转换为python中的可用值

时间:2016-05-20 21:44:15

标签: python-3.x

我试图将文件中的数据值转换为数组。到目前为止我所拥有的是

import os, io, struct, array

file=open('filename','rb')

myarray=[0]*1000

for i in range(100):
    myarray[i]=struct.unpack('i', file.read(4))

最终填充数组的内容类似于

((5,),(24,),(10,)....)

如何将其转换为

(5,24,10,...)

谢谢!

1 个答案:

答案 0 :(得分:0)

使用chain功能展平tuple tuple的<{1}}

from itertools import chain

result = ((5,),(24,),(10,))
result = tuple(chain(*result))
# (5, 24, 10)

您的代码应如此:

for i in range(100):
    myarray[i]=struct.unpack('i', file.read(4))

result = list(chain(*myarray[:100])) # you may want to keep this as a list