简体   繁体   English

将列表的字符串表示形式转换为列表

[英]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.

相关问题 将列表的字符串表示形式转换为Python中的列表 - Convert string representation of list to list in Python 如何将列表的字符串表示形式转换为列表 - How to convert string representation of list to a list 将列表列表的字符串表示形式转换为 python 中的列表 - convert a string representation of a list of lists to a list in python 将列表的字符串表示形式转换为字典 Python - Convert String representation of a List to a Dictionary Python 将颜色的字符串表示形式转换回列表 - Convert string representation of colors back to list 将列表列表的字符串表示形式转换为列表 python 的列表,无需 eval - Convert string representation of list of lists to list of list python without eval 当元素未包含在引号中时,将列表的字符串表示形式转换为列表 - Convert string representation of list to list when elements are not encased in quotes 如何将具有混合值的字符串表示列表转换为列表? - How to convert string representation list with mixed values to a list? python将整数嵌套列表的字符串表示形式转换为整数嵌套列表 - python convert string representation of nested list of integers to nested list of integers 当元素没有被引用时,将元组列表的字符串表示形式转换为列表 - Convert a string representation of a list of tuples to a list when elements are not quoted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM