我有一个清单:
['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']
我想变成一个整数元组列表,所以这个列表将变为:
[(128, 134), (134, 146), (134, 150), (137, 143), (137, 146), (137, 150), (143, 150)]
您可以literal_eval
从ast
模块中使用,它将安全地将字符串评估为 Python 表达式。
>>> a = ['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']
>>> from ast import literal_eval
>>> map(literal_eval, a)
[(128, 134), (134, 146), (134, 150), (137, 143), (137, 146), (137, 150), (143, 150)]
>>> import ast
>>> L = ['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']
>>> [ast.literal_eval(s) for s in L]
[(128, 134), (134, 146), (134, 150), (137, 143), (137, 146), (137, 150), (143, 150)]
import re
l=['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']
t = [ tuple(map (int, re.findall("\d+", v))) for v in l ]
print t
>>> L = ['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']
>>> [tuple(map(int, s.strip('()').split(', '))) for s in L]
[(128, 134), (134, 146), (134, 150), (137, 143), (137, 146), (137, 150), (143, 150)]
def to_tuple(x):
ints = x.strip('()').split()
return tuple(int(m.strip(',')) for m in ints)
print [to_tuple(a) for a in aa] # where aa is your string
只是 eval 会做
[eval(i) for i in a]