简体   繁体   English

python列表列表的用户可读文件格式

[英]User-readable file format for python list of lists

I'm considering using user-readable file format for my Python app. 我正在考虑为我的Python应用程序使用用户可读的文件格式。 Right now I'm using pickle to store my data in binary. 现在,我正在使用pickle将数据存储在二进制文件中。 I'm not sure if XML or JSON is a way to go but basically my file contains list of lists that looks like this: 我不确定是否可以使用XML或JSON,但是基本上我的文件包含如下所示的列表列表:

[1, 'the name of the set', [[1, 'data1', 'data2'],[2,'data3','data4']]

The list that hold the other lists containing the strings can have multiple items (even hundreds). 包含其他包含字符串的列表的列表可以有多个项目(甚至数百个)。 Basically, I'd like to have something that has easy interface to convert it to/from python list and I need those integers to stay integers. 基本上,我想拥有一个易于接口将其转换为python列表/从python列表转换的东西,我需要那些整数来保持整数。

I'd use YAML here specifically PyYAML ; 我会在这里专门使用YAML PyYAML IHMO it's much nicer to read for humans! IHMO对于人类来说,阅读起来要好得多!

Example: ( by hand ) 示例:( 手动

foo:
    - 1
    - 2
    - 3

Nesting excluded from above example 上例中排除的嵌套

Use: yaml.dump() and friends. 使用: yaml.dump()和朋友。

Demo: 演示:

>>> import yaml
>>> data = {"foo": [[1, 2, 3], [4, 5, 6]]}
>>> print yaml.dump(data)
foo:
- [1, 2, 3]
- [4, 5, 6]

NB: As JSON is a subset of YAML neither will preserve complex types; 注意:由于JSONYAML的子集,因此两者都不会保留复杂的类型。 only basic types are supported; 仅支持基本类型; int , float , list , dict and str . intfloatlistdictstr

That's already literal JSON. 那已经是文字JSON。 JSON's probably the most popular format out there, and it's hard to argue with its legibility. JSON可能是目前最流行的格式,很难辨认它的可读性。

In [105]: my_list = [1, 'the name of the set', [[1, 'data1', 'data2'],[2,'data3','data4']]]
In [106]: my_list == json.loads(json.dumps(my_list))
Out[106]: True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM