Parsing a string which represents a list of tuples(解析表示元组列表的字符串)
问题描述
我的字符串看起来像这样:
I have strings which look like this one:
"(8, 12.25), (13, 15), (16.75, 18.5)"
我想将它们中的每一个都转换成 python 数据结构.最好是包含一对浮点值的元组列表(或元组).
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.
我可以用 eval("(8, 12.25), (13, 15), (16.75, 18.5)")
来做到这一点,它给了我一个元组的元组,但我没有认为天真地评估外部信息将是一个明智的决定.
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.
所以我想知道一个优雅的 Pythonic 解决方案会是什么样子.
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))
这篇关于解析表示元组列表的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:解析表示元组列表的字符串


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01