将字符串(列表列表)转换为列表python
我想转换一个字符串将字符串(列表列表)转换为列表python,python,Python,我想转换一个字符串 '[["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-06-27", "iPhone", 6332817, 174833, "106
'[["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-07-03", "iPhone", 6347956, 187131, "1140332034.00000"], ["2018-07-03", "PC", 4413057, 166795, "1396042900.00000"], ["2018-07-03", "Android Mobile", 3840367, 107720, "639188845.00000"]]'
进入一个列表
我试过这样的东西
def str_to_list(raw_str):
ll =[]
raw_str = raw_str[1:-1]
pp1 = raw_str.split("],")
for i in pp1:
date , dc , visit, order, gms = i.strip().split(",")
print(date[2:-1] , dc[2:-1] , int(visit), int(order), gms[2:-1] )
:
使用ast.literal_eval,可以安全地计算表达式节点或包含Python表达式的字符串。提供的字符串或节点只能由以下Python文本结构组成:字符串、数字、元组、列表、dicts、boolean和None
到目前为止你试了什么?@eyllanesc我想你可能把错误的问题标记为重复的问题。用户希望将列表的字符串表示形式转换为列表。不展平列表。@PankajSinghal我只看到引号,我已经添加了它,我添加了缺少的副本。:)@是的@我的回答对你不起作用吗?您不必自己编写解析器。您可以使用
ast
模块
>>> a = '[["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-06-27", "iPhone", 6332817, 174833, "1060303510.00000"], ["2018-06-27", "PC", 4470497, 156399, "1251722217.00000"], ["2018-06-27", "Android Mobile", 3912827, 104684, "591207335.00000"], ["2018-07-03", "iPhone", 6347956, 187131, "1140332034.00000"], ["2018-07-03", "PC", 4413057, 166795, "1396042900.00000"], ["2018-07-03", "Android Mobile", 3840367, 107720, "639188845.00000"]]'
>>> import ast
>>> x = ast.literal_eval(a)
>>> x
[['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000'], ['2018-06-27', 'PC', 4470497, 156399, '1251722217.00000'], ['2018-06-27', 'Android Mobile', 3912827, 104684, '591207335.00000'], ['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000'], ['2018-06-27', 'PC', 4470497, 156399, '1251722217.00000'], ['2018-06-27', 'Android Mobile', 3912827, 104684, '591207335.00000'], ['2018-07-03', 'iPhone', 6347956, 187131, '1140332034.00000'], ['2018-07-03', 'PC', 4413057, 166795, '1396042900.00000'], ['2018-07-03', 'Android Mobile', 3840367, 107720, '639188845.00000']]
>>>
>>> x[0]
['2018-06-27', 'iPhone', 6332817, 174833, '1060303510.00000']
>>>