【发布时间】:2013-07-21 17:04:42
【问题描述】:
我有一个虚拟机,它从嵌套在一个列表中的元组中读取指令,如下所示:
[(0,4738),(0,36),
(0,6376),(0,0)]
在存储这种机器码程序时,文本文件是最简单的,必须写成字符串。这显然很难转换回来。
是否有任何模块可以将字符串读入列表/以可读的方式存储列表?
要求:
- 必须以存储形式可读(因此“pickle”不适合)
- 必须相对容易实施
【问题讨论】:
标签: python python-2.7
我有一个虚拟机,它从嵌套在一个列表中的元组中读取指令,如下所示:
[(0,4738),(0,36),
(0,6376),(0,0)]
在存储这种机器码程序时,文本文件是最简单的,必须写成字符串。这显然很难转换回来。
是否有任何模块可以将字符串读入列表/以可读的方式存储列表?
要求:
【问题讨论】:
标签: python python-2.7
使用json module:
string = json.dumps(lst)
lst = json.loads(string)
演示:
>>> import json
>>> lst = [(0,4738),(0,36),
... (0,6376),(0,0)]
>>> string = json.dumps(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = json.loads(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]
另一种方法是使用repr() 和ast.literal_eval();仅适用于还允许您往返的列表、元组和整数:
>>> from ast import literal_eval
>>> string = repr(lst)
>>> string
'[[0, 4738], [0, 36], [0, 6376], [0, 0]]'
>>> lst = literal_eval(string)
>>> lst
[[0, 4738], [0, 36], [0, 6376], [0, 0]]
JSON 的另一个优势是它是一种标准格式,并得到 Python 之外的工具的支持,支持序列化、解析和验证。 json 库也比 ast.literal_eval() 函数快很多。
【讨论】:
只需使用ast.literal_eval
>>> from ast import literal_eval
>>> a = literal_eval('[(1, 2)]')
>>> a
[(1, 2)]
您可以使用repr()将其转换为字符串。
>>> repr(a)
'[(1, 2)]'
【讨论】:
ast.literal_eval?
import json
with open(data_file, 'wb') as dump:
dump.write(json.dumps(arbitrary_data))
同样:
source = open(data_file, 'rb').read()
data = json.loads(source)
【讨论】:
eval 应该以简单的方式做到这一点:
>>> str([(0,4738),(0,36),(0,6376),(0,0)])
'[(0, 4738), (0, 36), (0, 6376), (0, 0)]'
>>> eval(str([(0,4738),(0,36),(0,6376),(0,0)]))
[(0, 4738), (0, 36), (0, 6376), (0, 0)]
【讨论】:
如果你只是处理原始的 Python 类型,你可以使用内置的repr():
Help on built-in function repr in module __builtin__:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
【讨论】:
如果这些只是两个元组,您可以使用 csv module 将它们存储在 CVS 文件中。不需要任何括号/括号。
【讨论】:
with open('path/to/file', 'w') as outfile:
for tup in L:
outfile.write("%s\n" %' '.join(str(i) for i in tup))
with open('path/to/file) as infile:
L = [tuple(int(i) for i in line.strip().split()) for line in infile]
【讨论】: