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

2024-05-15 03:10:11 发布

您现在位置:Python中文网/ 问答频道 /正文

所以给定一个列表的文本表示

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

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


Tags: 文本脚本列表group中将cellularorganismsbacteria
1条回答
网友
1楼 · 发布于 2024-05-15 03:10:11
>>> 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.

相关问题 更多 >

    热门问题