简体   繁体   English

如何在Python中保存2D数组(列表)?

[英]How to save 2D arrays (lists) in Python?

I need to save a 2D array representing a map in the game world to a configparser. 我需要将表示游戏世界中地图的2D数组保存到configparser中。 The data looks like this: 数据如下所示:

[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]

As an example. 举个例子。

I can obviously save the data but I can't convert it from a string back to a list after reading it back in... 我显然可以保存数据,但是在读回数据后无法将其从字符串转换回列表...

I don't mind if I have to use a .txt file instead, by the way, and just read it in with the normal text file handler. 顺便说一句,我不介意是否必须使用.txt文件,并使用普通的文本文件处理程序将其读取。

Python has a module for saving Python data called pickle . Python有一个名为pickle用于保存Python数据的模块。 You can use that. 您可以使用它。 From the docs: 从文档:

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. pickle模块实现了一个基本但功能强大的算法,用于对Python对象结构进行序列化和反序列化。 “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. “ Pickling”是将Python对象层次结构转换为字节流的过程,而“ unpickling”是逆运算,从而字节流被转换回对象层次的过程。 Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” 1 or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”. 酸洗(和解酸)也称为“序列化”,“编组”,“ 1”或“展平”,但是,为避免混淆,此处使用的术语为“酸洗”和“解酸”。

Demo: 演示:

>>> import pickle
>>> data = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
>>> with open('C:/temp/pickle_test.data', 'w') as f:
    pickle.dump(data, f)


>>> with open('C:/temp/pickle_test.data', 'r') as f:
    new_data = pickle.load(f)


>>> new_data
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]

You can do it using a simple eval 您可以使用简单的评估

>>> x="[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]"
>>> type(x);
<type 'str'>
>>> y=eval(x);
>>> print(y);
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
>>>type(y);
<type 'list'>

It's a very quick and dirty solution, you should use more secure and good input files parsers (like pickle). 这是一个非常快速和肮脏的解决方案,您应该使用更安全,性能更好的输入文件解析器(例如pickle)。

For the transformation of a string to a list you could do something like this: 为了将字符串转换为列表,您可以执行以下操作:

myList = [x for x in "0,1,2,3".split(",")]
type(myList)
<type 'list'>
print myList
['0', '1', '2', '3']

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

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