如何在Python 3.7中将复杂列表转换为字符串并返回?

时间:2019-02-19 13:52:47

标签: python python-3.x python-3.7

我正在尝试将Python列表保存到文件中,然后在我重新启动程序时再次读取它们。问题是我的列表很复杂:即元组中的元组数量不同。

我能想到的最好的办法是最初将列表转换为字符串(可以使用),但是我想不出办法还原更改。

with open(filename, 'w') as f:
            f.write(str(objs))
            f.close()

这有效,但是如何将其返回列表?

只是为了阐明我对复杂列表的定义是什么,下面是一个示例:

[(((0.0, 0.0, 0.0), (1000.0, 0.0, 0.0), (0.0, 2.0, 0.0), (1000.0, 2.0, 
0.0), (0.0, 0.0, 1000.0), (1000.0, 0.0, 1000.0), (0.0, 2.0, 1000.0), 
(1000.0, 2.0, 1000.0)), ((0, 2, 3, 1), (4, 6, 7, 5), (1, 3, 7, 5), (4, 6, 
2, 0), (2, 6, 7, 3), (4, 0, 1, 5)), ((255, 0, 0), (255, 128, 0), (255, 255, 
0), (255, 255, 255), (0, 0, 255), (0, 255, 0)))]

2 个答案:

答案 0 :(得分:3)

正如@snakecharmerb所述,您可以使用jsonpickle。这是一个示例:

代码:

my_list = [(((0.0, 0.0, 0.0), (1000.0, 0.0, 0.0), (0.0, 2.0, 0.0), (1000.0, 2.0, 
0.0), (0.0, 0.0, 1000.0), (1000.0, 0.0, 1000.0), (0.0, 2.0, 1000.0), 
(1000.0, 2.0, 1000.0)), ((0, 2, 3, 1), (4, 6, 7, 5), (1, 3, 7, 5), (4, 6, 
2, 0), (2, 6, 7, 3), (4, 0, 1, 5)), ((255, 0, 0), (255, 128, 0), (255, 255, 
0), (255, 255, 255), (0, 0, 255), (0, 255, 0)))]

import json

with open('my_list.json', 'w') as f:
    json.dump(my_list, f)

with open('my_list.json','r') as f:
    loaded_list = json.load(f)

print('Using json:')
print(loaded_list)

import pickle

with open('my_list.pkl', 'wb') as f:
    pickle.dump(my_list, f)

with open('my_list.pkl', 'rb') as f:
    loaded_list = pickle.load(f)

print('Using pickle:')
print(loaded_list)

输出:

Using json:
[[[[0.0, 0.0, 0.0], [1000.0, 0.0, 0.0], [0.0, 2.0, 0.0], [1000.0, 2.0, 0.0], [0.0, 0.0, 1000.0], [1000.0, 0.0, 1000.0], [0.0, 2.0, 1000.0], [1000.0, 2.0, 1000.0]], [[0, 2, 3, 1], [4, 6, 7, 5], [1, 3, 7, 5], [4, 6, 2, 0], [2, 6, 7, 3], [4, 0, 1, 5]], [[255, 0, 0], [255, 128, 0], [255, 255, 0], [255, 255, 255], [0, 0, 255], [0, 255, 0]]]]

Using pickle:
[(((0.0, 0.0, 0.0), (1000.0, 0.0, 0.0), (0.0, 2.0, 0.0), (1000.0, 2.0, 0.0), (0.0, 0.0, 1000.0), (1000.0, 0.0, 1000.0), (0.0, 2.0, 1000.0), (1000.0, 2.0, 1000.0)), ((0, 2, 3, 1), (4, 6, 7, 5), (1, 3, 7, 5), (4, 6, 2, 0), (2, 6, 7, 3), (4, 0, 1, 5)), ((255, 0, 0), (255, 128, 0), (255, 255, 0), (255, 255, 255), (0, 0, 255), (0, 255, 0)))]

您会看到json将元组转换为列表。

答案 1 :(得分:1)

import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Dense from tensorflow.python.keras.wrappers.scikit_learn import KerasRegressor seed = 7 np.random.seed(seed) dataset=np.loadtxt("N_LANDCOV.csv", delimiter=",") x=dataset[:,:-1] y=dataset[:,-1] y=np.reshape(y, (-1,1)) scaler = MinMaxScaler() print(scaler.fit(x)) print(scaler.fit(y)) xscale=scaler.transform(x) yscale=scaler.transform(y) X_train, X_test, y_train, y_test = train_test_split(xscale, yscale) model = Sequential() model.add(Dense(28, input_dim=12, kernel_initializer='normal', activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(1, activation='linear')) model.summary() model.compile(loss='mse', optimizer='adam', metrics=['mse','mae']) history = model.fit(X_train, y_train, epochs=1000, batch_size=10, verbose=1, validation_split=0.33) Epoch 1000/1000 30/30 [==============================] - 0s 702us/step - loss: 0.0517 - mean_squared_error: 0.0517 - mean_absolute_error: 0.1988 - val_loss: 0.0357 - val_mean_squared_error: 0.0357 - val_mean_absolute_error: 0.1416 import os os.environ['KMP_DUPLICATE_LIB_OK']='True' print(history.history.keys()) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() plt.figure(figsize=(200, 200)) 函数会将复杂列表/嵌套列表和元组转换为字符串 此外,str将任何字符串转换为实际的代码段

但是,正如Taras Savchyn所提到的,eval可能导致SQL注入等等。因此,请改用eval

因此:

ast.literal_eval

希望这可以解决您的问题。您可以评论答案以询问其他任何问题