Convert strings of list to list of integers inside a list

前端 未结 5 1603
长发绾君心
长发绾君心 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:31

    It is often not recommended, but you could use eval for each string:

    fun = ['[1,2,3]','[10,12,5]']
    listy = [eval(x) for x in fun]
    

    Outputs:

    [[1, 2, 3], [10, 12, 5]]
    

    This question provides excellent reason as to why using eval can be a bad idea. I am just presenting it here as an option. eval can pose a large security risk, as you are giving user input the full power of the Python interpreter. Additionally, it violates one of the fundamental principles of programming, which states that all of your executable code should directly map to your source code. Evaluating user input with eval leads to executable code that evidently isn't in your source.

    Using ast.literal_eval() is preferable, and Padraic Cunningham's answer addresses how to use it effectively.

提交回复
热议问题