[英]Convert string representation of list into list
list_string = "[1,3,4,6]"
I tried list_string[1:-1]
but it is giving 1,3,4,6
. 我尝试了
list_string[1:-1]
但它给出了1,3,4,6
。 I also tried list_string.split(',')
but again the brackets will be appended to first and last element ie '[1' , '3' , '4' , '6]'
我也尝试过
list_string.split(',')
但是括号将再次附加到第一个和最后一个元素,即'[1' , '3' , '4' , '6]'
I can iterate over all the items and remove brackets from 1st and last element. 我可以遍历所有项目,并从第一个元素和最后一个元素中删除括号。 But what is the best and simple way to do this?
但是,最佳和简单的方法是什么?
Assuming your string is a simple list/dict/combination of lists and dicts, you can use one of the two packages mentioned below, listed in order of preference. 假设您的字符串是列表和字典的简单列表/字典/组合,则可以使用下面提到的两个软件包之一,按优先顺序列出。
json
>>> import json
>>> json.loads('[1, 2, 3]')
[1, 2, 3]
This is definitely the preferred method if you are parsing raw json strings. 如果您要解析原始json字符串,则绝对是首选方法。
ast.literal_eval
>>> import ast
>>> ast.literal_eval('[1, 2, 3]')
[1, 2, 3]
ast.literal_eval
will safely evaluate an expression node or a string containing a Python literal or container display. ast.literal_eval
将安全地评估表达式节点或包含Python文字或容器显示的字符串。 The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets. 提供的字符串或节点只能由以下Python文字结构组成:字符串,字节,数字,元组,列表,字典,集合,布尔值,无,字节和集合。
Also json.loads
is significantly faster than ast.literal_eval
. 而且
json.loads
明显比ast.literal_eval
快 。 Use this ONLY IF you cannot use the json
module first. 仅当您不能首先使用
json
模块json
使用此功能。
yaml
In some cases, you can also use the pyYAML library (you'll need to use PyPi to install it first). 在某些情况下,您还可以使用pyYAML库(首先需要使用PyPi进行安装)。
>>> import yaml
>>> yaml.safe_load('[1, 2, 3]')
[1, 3, 4, 6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.