python - 将字符串封闭列表转换为列表

标签 python string list

<分区>

我正在尝试将引号中包含的列表转换为列表。他们是执行此操作的最佳方法吗?

Ex: list = "[1,2,3,4,5]"

Operation : Convert list which is string to a list

o/p: list = [1,2,3,4,5]

最佳答案

您可以使用 ast.literal_eval()安全地评估字符串:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

In [1]: from ast import literal_eval

In [2]: literal_eval("[1,2,3,4,5]")
Out[2]: [1, 2, 3, 4, 5]

关于python - 将字符串封闭列表转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43752490/

相关文章:

c++ - 哪个更好地检查 std::string 中是否存在字符?查找还是 find_first_of?

c++ - 如何在 C++ 中声明 std::chrono::duration<double> 变量

R - 当名称在变量中时按名称提取列表元素

python - 优化用于从预定义范围确定合格分数的算法

python - 如何在python中将telnet输出日志保存到文本文件

python - 使用 Django 和 AJAX 的动态 HTML 页面的最小示例

python - 格式化二维网格中的路径打印

c++ - 使用 std::string 构造函数复制 const char *

C - 将两个字符数组交织在一起时出现异常结果

java - 如何使用集合添加列表(字符串数组)和arrayList?