字符串列表到整数元组列表中

时间:2013-04-23 06:33:31

标签: python list

我有一个清单:

['(128, 134)', '(134, 146)', '(134, 150)', '(137, 143)', '(137, 146)', '(137, 150)', '(143, 150)']

我想变成一个int元组的列表,所以这个列表将成为:

[(128, 134), (134, 146), (134, 150), (137, 143), (137, 146), (137, 150), (143, 150)]

6 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:3)

您可以使用ast模块中的literal_eval来安全地将字符串评估为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)]

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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)]

答案 5 :(得分:0)

只是eval会做

[eval(i) for i in a]