将看起来像列表的字符串转换为真正的列表 - python
问题描述
我的输入文件的行如下所示:
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]
没有字母,没有小数,只有整数和元组中的元素个数一致.
There are no letters, no decimals, only integers and number of element in tuples will be consistent.
如何将它们变成真正的元组列表/int 列表?
How do i make them into real list of tuples / list of int?
解决方案
Python 自带电池 - ast.literal_eval()
:
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]
相关文章