解析一个表示元组列表的字符串 [英] Parsing a string which represents a list of tuples

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

问题描述

我的字符串看起来像这样:

 (8,12.25),(13,15),( 16.75,18.5)

我想把它们转换成一个python数据结构。我们可以用 eval((8,12.25)来实现这个功能,这个元组最好包含一个包含一对浮点值的元组的列表(或元组)。



< ,(13,15),(16.75,18.5))
这给我一个元组元组,但我不认为天真地评估外部信息是一个明智的决定。 b
$ b

所以我想知道一个优雅的pythonic解决方案可能是什么样子。

解决方案

 >>> import ast 
>>>>打印ast.literal_eval((8,12.25),(13,15),(16.75,18.5))
((8,12.25),(13,15),(16.75,18.5))


I have strings which look like this one:

"(8, 12.25), (13, 15), (16.75, 18.5)"

and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values.

I could do that with eval("(8, 12.25), (13, 15), (16.75, 18.5)") which gives me a tuple of tuples, but I don't think naively evaluating external information would be a wise decision.

So I wondered what an elegant pythonic solution might look like.

解决方案

>>> import ast
>>> print ast.literal_eval("(8, 12.25), (13, 15), (16.75, 18.5)")
((8, 12.25), (13, 15), (16.75, 18.5))

这篇关于解析一个表示元组列表的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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