简体   繁体   中英

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'

I am new to Python.

You can use 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 :

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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