python - 将 Python 中的打印列表转换回实际列表的最佳方法是什么

标签 python string list

给定一个列表的文本表示

['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes',   'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']

在 python 脚本中将此文本转换回实际列表的最简单方法是什么? 拆分真的是最好的方法吗?谢谢!

最佳答案

>>> import ast
>>> a = "['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes',   'Bacteroidiroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']"
>>> ast.literal_eval(a)
['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']

来自ast module :

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

关于python - 将 Python 中的打印列表转换回实际列表的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22322577/

相关文章:

python - 如何从列表中选择一个与之前不同的随机整数?

Python concat字符串与列表

python - 将 {} 绑定(bind)到 future 版本的 dict()

python - 我有一个 numpy 数组和一个索引数组,如何同时访问这些位置

python - 随机梯度下降的批量大小是训练数据的长度而不是 1?

C函数输入字符串

C++ : List iterator not incrementable

python - 全局框架与堆栈框架

c++ - 从用户输入中获取 mm dd yyyy

Ruby - 从另一个方法中提取我的较小方法(将字符串转换为两个数字和一个符号)