将字符串元组转换为元组 [英] Convert string-tuple to a tuple

查看:51
本文介绍了将字符串元组转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

[(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)], '减', 3...

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

例如,行 string "[(1,1),(2,1)], 'add', 11" 应转换为元组:([(1, 1), (2, 1)], 'add', 11).

到目前为止,我尝试过:

元组 = []对于文件中的行: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)], '减号', 3",)]

解决方案

您可以使用 ast.literal_eval 为:

<预><代码>>>>进口AST>>>my_string = "[(1,1),(2,1)], 'add', 11">>>ast.literal_eval(my_string)([(1, 1), (2, 1)], '添加', 11)

根据 ast.literal_eval(node_or_string) 文档:

<块引用>

安全地计算包含 Python 文字或容器显示的表达式节点或 Unicode 或 Latin-1 编码字符串.提供的字符串或节点只能由以下 Python 文字结构组成:字符串、数字、元组、列表、字典、布尔值和无.

I have an input file with the following format:

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

Each line is a tuple I want to create. How is it possible to convert each string line into a tuple?

For example, line string "[(1,1),(2,1)], 'add', 11" should be converted to a tuple: ([(1, 1), (2, 1)], 'add', 11).

So far, I tried:

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

But I am getting a string conversion

 [("[(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",)]

解决方案

You may use ast.literal_eval as:

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

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

As per the 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.

这篇关于将字符串元组转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆