gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:41 24 4
gpt4 key购买 nike

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

[(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
...

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

例如,行 string "[(1,1),(2,1)], 'add', 11" 应转换为元组:([(1 , 1), (2, 1)], '添加', 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 - 将字符串元组转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41150857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com