How to convert a string of a list of tuples to a Python list of tuples [duplicate]

孤街浪徒 提交于 2020-01-05 02:31:09

问题


I have a list of tuples saved into a string (unfortunately). I am looking for a fast an efficient way to convert this string to an actual list of tuples.

Example:

mylist_string = '[(40.7822603, -73.9525339), (40.7142, -74.0087), (40.7250027, -73.9413106), (40.703422, -73.9862948), (40.7169963, -74.0149991), (40.7420448, -73.9918131), (40.7287, -73.9799), (40.7757237, -73.9492357), (40.7169904, -73.9578252), (40.726103, -73.9780367), (40.7776792, -73.9585829), (40.6750972, -73.9679734), (40.6867687, -73.9743078), (40.6684762, -73.9755826), (40.7169, -73.9578), (40.6996798, -73.9291393), (40.6680182, -73.9809183), (40.7346, -74.0073), (40.6871087, -73.9741862), (40.7160416, -73.9452393), (40.7178984, -74.0063829)]'

the expected output is a list of tuples in Python.

Thanks


回答1:


This is one way:

import ast

ast.literal_eval(mystr)

# [(40.7822603, -73.9525339),
#  (40.7142, -74.0087),
#  (40.7250027, -73.9413106),
#  (40.703422, -73.9862948),
# ...
#  (40.6871087, -73.9741862),
#  (40.7160416, -73.9452393),
#  (40.7178984, -74.0063829)]



回答2:


eval(mylist_string)

This will evaluate your string as if you typed it in Python.

Edit: this is an answer to the question, but it is not a good answer. There are security risks and it might not do what you think it does. So don't use eval, use:

import ast

ast.literal_eval(mystr)

See [this SO question] for a detailed comparison.



来源:https://stackoverflow.com/questions/48715893/how-to-convert-a-string-of-a-list-of-tuples-to-a-python-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!