简体   繁体   English

将字符串列表转换为int元组列表

[英]list of strings into a list of tuples of ints

I have a list: 我有一个清单:

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

I want to turn into a list of tuples of ints so this list will become: 我想变成一个整数元组列表,所以该列表将变为:

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

You can use literal_eval from the ast module which will safely evaluate a string as a Python expression. 您可以使用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)]
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
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)]

只是评估会做

[eval(i) for i in a]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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