如何将元组列表的字符串转换为Python的元组列表 [英] How to convert a string of a list of tuples to a Python list of tuples

查看:94
本文介绍了如何将元组列表的字符串转换为Python的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存在字符串中的元组列表(不幸的是).我正在寻找一种快速有效的方法将此字符串转换为实际的元组列表.

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.

示例:

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

预期输出是Python中的元组列表.

the expected output is a list of tuples in Python.

谢谢

推荐答案

这是一种方法:

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

这篇关于如何将元组列表的字符串转换为Python的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆