python-将字符串元组转换为元组

我有一个具有以下格式的输入文件:

[(1,1),(2,1)], 'add', 11
[(1,2),(1,3)], 'div', 2
[(3,1),(4,1),(3,2),(4,2)], 'times', 240
[(2,2),(2,3)], 'minus', 3
             .
             .

每行都是我要创建的元组.如何将每个字符串行转换为元组.

例如:

line: string "[(1,1),(2,1)], 'add', 11" ---------> tuple: [ [(1,1),(2,1)], 'add', 11]

到目前为止,我尝试了:

tuples = []
for line in file:
    tuples.append((line,))

但是我正在转换字符串

 [("[(1,1),(2,1)], 'add', 11\n",), ("[(1,2),(1,3)], 'div', 2\n",), ("[(3,1),(4,1),(3,2),(4,2)], 'times', 240\n",), ("[(2,2),(2,3)], 'minus', 3",)]

解决方法:

您可以将ast.literal_eval用作:

>>> import ast
>>> my_string = "[(1,1),(2,1)], 'add', 11"

>>> ast.literal_eval(my_string)
([(1, 1), (2, 1)], 'add', 11)

根据ast.literal_eval(node_or_string) document

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

上一篇:python – str.startswith如何真正起作用?


下一篇:python-除字母数字排序外,按键对字典项进行排序