Converting string that looks like a list into a real list - python

前端 未结 1 1253
感情败类
感情败类 2020-12-16 23:46

My input files have lines that looks like this:

[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]
[1,2,3,5,3]


        
相关标签:
1条回答
  • 2020-12-17 00:41

    Python comes with batteries included - that problem is solved by ast.literal_eval():

    >>> import ast
    >>> ast.literal_eval("[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]")
    [(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
    >>> ast.literal_eval("[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]")
    [(0, 1, 6), (1, 3, 7), (3, 1, 4), (3, 1, 3), (8, 1, 2)]
    >>> ast.literal_eval("[1,2,3,5,3]")
    [1, 2, 3, 5, 3]
    
    0 讨论(0)
提交回复
热议问题