将列表的字符串表示形式转换为列表 [英] Convert string representation of list into list

查看:815
本文介绍了将列表的字符串表示形式转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list_string = "[1,3,4,6]"

我尝试了list_string[1:-1],但是它给出了1,3,4,6. 我也尝试过list_string.split(','),但再次将括号添加到第一个和最后一个元素,即'[1' , '3' , '4' , '6]'

I tried list_string[1:-1] but it is giving 1,3,4,6. I also tried list_string.split(',') but again the brackets will be appended to first and last element i.e '[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.

>>> import json
>>> json.loads('[1, 2, 3]')
[1, 2, 3]

如果要解析原始json字符串,这绝对是首选方法.

This is definitely the preferred method if you are parsing raw json strings.

>>> import ast
>>> ast.literal_eval('[1, 2, 3]')
[1, 2, 3]

ast.literal_eval将安全地评估包含Python文字或容器显示的表达式节点或字符串.提供的字符串或节点只能由以下Python文字结构组成:字符串,字节,数字,元组,列表,字典,集合,布尔值,无,字节和集合.

ast.literal_eval will 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, None, bytes and sets.

ast.literal_eval 快得多.仅当您不能先使用json模块时才使用此功能.

Also json.loads is significantly faster than ast.literal_eval. Use this ONLY IF you cannot use the json module first.

在某些情况下,您还可以使用pyYAML库(首先需要使用PyPi进行安装).

In some cases, you can also use the pyYAML library (you'll need to use PyPi to install it first).

>>> import yaml
>>> yaml.safe_load('[1, 2, 3]')
[1, 3, 4, 6] 

这篇关于将列表的字符串表示形式转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆