简体   繁体   English

如何将表示元组的字符串列表转换为整数元组?

[英]How to convert a list of strings representing tuples to tuples of integers?

I want to convert 我想转换

list_int=['(2,3)','(3,4)']

to integer coordinate points: 到整数坐标点:

[(2, 3), (4, 8)]

I tried this code 我尝试了这段代码

list_int=['(2,3)','(3,4)']
for x in list_int:
    con= int(x0 for x in list_int)
    print con

and I am getting this error 我得到这个错误

TypeError: int() argument must be a string or a number, not 'generator' TypeError:int()参数必须是字符串或数字,而不是'generator'

I am new to Python. 我是Python的新手。

You can use ast.literal_eval : 您可以使用ast.literal_eval

from ast import literal_eval

list_int=['(2,3)','(3,4)'] 

converted = [literal_eval(tup) for tup in list_int]

# [(2, 3), (3, 4)]

From the doc of ast.literal_eval : 来自ast.literal_eval的文档:

Safely evaluate an expression node or a string containing a Python literal or container display. 安全地评估表达式节点或包含Python文字或容器显示的字符串。 The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. 提供的字符串或节点只能由以下Python文字结构组成:字符串,字节,数字,元组,列表,字典,集合,布尔值和无。

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. 这可用于安全地评估包含来自不受信任来源的Python值的字符串,而无需自己解析值。 It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing. 它不能评估任意复杂的表达式,例如涉及运算符或索引的表达式。

我将删除开始和结束括号,分割每个字符串,然后将每个元素转换为一个int

result = [[int(x) for x in s[1:-1].split(",")] for s in list_int]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM