【问题标题】:Writing data types to a CSV将数据类型写入 CSV
【发布时间】:2019-06-19 07:14:13
【问题描述】:

我的程序会生成一个锻炼程序。此锻炼程序保存在二维数组中。然后将锻炼程序写入 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 文件,或者以一种在检索时使其成为数组的方式检索它?或者我可以将字符串转换为数组吗?

【问题讨论】:

  • “哑铃”有两个 b。

标签: python arrays types


【解决方案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'>

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2017-03-14
    • 2016-03-27
    • 2021-05-17
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多