簡體   English   中英

將字符串列表轉換為int元組列表

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

我有一個清單:

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

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

您可以使用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