使用PythonZip将数据保存在二进制文件的不同列中
我有以下数据文件:使用PythonZip将数据保存在二进制文件的不同列中,python,file-io,binaryfiles,Python,File Io,Binaryfiles,我有以下数据文件: 0.0 2453.4645 4906.929 7360.3935 9813.858 12267.3225 14720.787 17174.2515 19627.716 22081.1805 24534.645 26988.1095 29441.574 31895.0385 34348.503 36801.9675 以二进制形式 我需要将其读入8个列表a、b、c、d、e、f、g、h,每个列表有3个元素。i、 e.我需要在每个变
0.0 2453.4645 4906.929 7360.3935 9813.858 12267.3225 14720.787 17174.2515 19627.716 22081.1805 24534.645 26988.1095 29441.574 31895.0385 34348.503 36801.9675
以二进制形式
我需要将其读入8个列表a、b、c、d、e、f、g、h,每个列表有3个元素。i、 e.我需要在每个变量中保存元素1-8,然后是9-16,依此类推
我有以下代码:
# Python code to read binary data
from struct import *
import numpy as np
readfile = open('bigdata.dat')
readfile_data = readfile.read()
type(readfile_data)
a = len(readfile_data)
print a
e = unpack('18d',readfile_data[0:8*18])
field_names = ('a','b','c','d','e','f')
hg = dict(zip(field_names,e))
print hg
我得到的是一个dict,每个dictionary值都有一个元素:
{'a': 0.0, 'c': 4906.929, 'b': 2453.4645, 'e': 9813.858, 'd': 7360.3935, 'f': 12267.3225}
如何在Python中实现这一点(最好是2.7,但也欢迎使用3)?我想我必须循环
在整个列表中覆盖这些字典字段名,但我不知道如何..一旦您以列表形式获得数据,您就可以执行类似的操作
from collections import defaultdict
data = [[0.0, 2453.4645, 4906.929, 7360.3935,
9813.858, 12267.3225, 14720.787,
17174.2515], [19627.716, 22081.1805,
24534.645, 26988.1095, 29441.574,
31895.0385, 34348.503, 36801.9675]]
hg = defaultdict(list)
field_names = ('a','b','c','d','e','f')
for row in data:
for field_name, datum in zip(field_names, row):
hg[field_name].append(datum)
print hg
哪个输出
defaultdict(<type 'list'>, {'a': [0.0, 19627.716], 'c': [4906.929, 24534.645], 'b': [2453.4645, 22081.1805], 'e': [9813.858, 29441.574], 'd': [7360.3935, 26988.1095], 'f': [12267.3225, 31895.0385]})
defaultdict(,{'a':[0.019627.716],'c':[4906.929292944534.645],'b':[2453.464522081.1805],'e':[9813.85829441.574],'d':[7360.393526988.1095],'f':[12267.32251895.0385])
itertools模块有一个islice()
功能,可以帮助您:
>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> import itertools
>>> for val in itertools.islice(s, 0, None, 8):
... print val
...
a
i
q
y
>>> for val in itertools.islice(s, 1, None, 8):
... print val
...
b
j
r
z
>>> for val in itertools.islice(s, 2, None, 8):
... print val
...
c
k
s
因此,对于您的问题,您可以:
import itertools
a = [item for item in itertools.islice(e, 0, None, 8)]
b = [item for item in itertools.islice(e, 1, None, 8)]
c = [item for item in itertools.islice(e, 2, None, 8)]
等等。或者,更好的是:
columns = []
for n in range(8):
columns.append([item for item in itertools.islice(e, n, None, 8)])
希望这有帮助
顺便说一下,这是你的答案。
itertools
模块中还有很多其他有用的工具:看看 我认为这不是他想要的。他希望“a”有第0个和第8个值,“b”有第1个和第9个值,依此类推。如果您不熟悉[x在某些迭代器中表示x]
符号,那么它就是a。它们非常有用,非常值得你去思考:使用它们可以让你的代码更加简洁,也更容易阅读,只要你不想在一行中塞进太多内容问题是为什么我在最后一个例子中没有使用第二个列表理解。模式somelist=[];对于某些迭代器中的值:somelist.append(dosomething\u with(value))
是一个典型的符号,表明您应该使用列表理解。。。但在最后一个例子中,它最终将成为两个相互嵌套的列表理解。这本可以很好地工作,但是如果您不非常了解Python,那么阅读起来会非常困难。