Convert strings of list to list of integers inside a list

前端 未结 5 1623
长发绾君心
长发绾君心 2021-01-28 20:02

I have a list of strings and those strings are lists. Like this: [\'[1,2,3]\',\'[10,12,5]\'], for example. I want to get a list of lists or even every list there: <

5条回答
  •  感情败类
    2021-01-28 20:33

    You should use literal_eval to get actual list object from string.

    >>> from ast import literal_eval
    >>> data =  ['[1,2,3]','[10,12,5]']
    >>> data = [literal_eval(each) for each in data]
    >>> data
    [[1, 2, 3], [10, 12, 5]]
    

    literal_eval safely evaluates each object.

    >>> help(literal_eval)
    Help on function literal_eval in module ast:
    
    literal_eval(node_or_string)
        Safely evaluate an expression node or a string containing a Python
        expression.  The string or node provided may only consist of the following
        Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
        and None.
    

    You should always try to avoid using eval function. Read more here.

提交回复
热议问题