0

我有一个清单:

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

4

6 回答 6

3

您可以literal_evalast模块中使用,它将安全地将字符串评估为 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)]
于 2013-04-23T06:39:38.647 回答
3
>>> 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)]
于 2013-04-23T06:36:35.637 回答
0
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
于 2013-04-23T06:40:33.070 回答
0
>>> 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)]
于 2013-04-23T06:52:12.260 回答
0
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
于 2013-04-23T06:39:17.690 回答
0

只是 eval 会做

[eval(i) for i in a]
于 2013-04-23T09:23:31.187 回答