将字符串(列表列表)转换为列表python

时间:2018-07-04 08:02:22

标签: 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, "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] )

1 个答案:

答案 0 :(得分:1)

>>> 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']
>>> 

ast.literal_eval

  

使用ast.literal_eval,您可以安全地评估表达式节点或包含Python表达式的字符串。提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无。