将数据类型写入CSV

时间:2019-01-25 12:38:12

标签: python arrays types

我的程序生成锻炼程序。该锻炼程序保存在二维数组中。然后,将锻炼程序写入CSV文件。但是,当用户登录时,锻炼例程会作为字符串从CSV文件中提取。因此,我没有办法从阵列中进行单个练习。 锻炼例程被写入名为user_information

的数组中

这就是检索到的user_information的样子(保存为字符串格式)

[['Bench Press', 'Dumbell Press', 'Rotating Incline Dumbell Press', 'Inner Chest Upwards Barbell Push', 'Reverse Flies', 'Cable Side Raise', 'Overhead Barbell Extensions'], ['Drop Set Curls', 'Close Grip Chin Ups', 'Upright Row', 'Pullups', 'One Arm Cable Pull', 'Lat Pulldowns'], ['Calf Raisers', 'Leg Extensions', 'Squats', 'Rear Kicks', 'Abductor']]"]

无论如何,我是否可以将数据类型写入CSV文件,或以使其在检索时成为数组的方式进行检索?还是可以将字符串转换为数组?

1 个答案:

答案 0 :(得分:1)

您可以使用ast模块将字符串转换为列表对象。

例如:

import ast 

#Data read from CSV
user_information  = "[['Bench Press', 'Dumbell Press', 'Rotating Incline Dumbell Press', 'Inner Chest Upwards Barbell Push', 'Reverse Flies', 'Cable Side Raise', 'Overhead Barbell Extensions'], ['Drop Set Curls', 'Close Grip Chin Ups', 'Upright Row', 'Pullups', 'One Arm Cable Pull', 'Lat Pulldowns'], ['Calf Raisers', 'Leg Extensions', 'Squats', 'Rear Kicks', 'Abductor']]"
print(ast.literal_eval(user_information))
print(type(ast.literal_eval(user_information)))

输出:

[['Bench Press', 'Dumbell Press', 'Rotating Incline Dumbell Press', 'Inner Chest Upwards Barbell Push', 'Reverse Flies', 'Cable Side Raise', 'Overhead Barbell Extensions'], ['Drop Set Curls', 'Close Grip Chin Ups', 'Upright Row', 'Pullups', 'One Arm Cable Pull', 'Lat Pulldowns'], ['Calf Raisers', 'Leg Extensions', 'Squats', 'Rear Kicks', 'Abductor']]
<type 'list'>