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

标签 python python-2.7

我要转换

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

到整数坐标点:

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

我尝试了这段代码

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

我收到此错误

TypeError: int() argument must be a string or a number, not 'generator'

我是 Python 新手。

最佳答案

您可以使用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)]

来自 ast.literal_eval 的文档:

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

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

关于python - 如何将表示元组的字符串列表转换为整数元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52571612/

相关文章:

Python 正则表达式将查找由特定字母组成的单词。字母只能使用一次

python - 定时任务 |缺少 Python 模块

python - 不可能的反向引用

python - 为什么 list(xrange) 比 range() 慢?

python - 与 parent 一起杀死 child

python - 自定义 Transformer 单独工作,但将它们组合成一个 Pipeline 时会崩溃

python - 使用for循环的结果在python中创建新列表

python - 为什么正则表达式在 Python 2.7 中匹配一个额外的空格?

python - 使用 Python 2.7.9 的 TWOSQRS SPOJ 给出运行时错误 (NZEC)

python - 随机分配 pandas DataFrame 功能