将Python中列表的字符串表示形式转换为列表
由于Python处理各种数据类型,我们会遇到列表以字符串形式出现的情况。在本文中,我们将了解如何将字符串转换为列表。
使用strip和split
我们首先应用strip方法去除方括号,然后应用split函数。使用逗号作为参数的split函数从字符串创建列表。
示例
stringA = "[Mon, 2, Tue, 5,]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = stringA.strip('][').split(', ')
# Result and its type
print("final list", res)
print(type(res))输出
运行以上代码,得到以下结果:
Given string [Mon, 2, Tue, 5,] final list ['Mon', '2', 'Tue', '5,']
使用json.loads
json模块可以直接将字符串转换为列表。我们只需传入字符串作为参数即可应用该函数。这里我们只能考虑数值元素。
示例
import json
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = json.loads(stringA)
# Result and its type
print("final list", res)
print(type(res))输出
运行以上代码,得到以下结果:
Given string [21,42, 15] final list [21, 42, 15]
使用ast.literal_eval
ast模块提供literal_eval函数,可以直接将字符串转换为列表。我们只需将字符串作为参数传递给literal_eval方法即可。这里我们只能考虑数值元素。
示例
import ast
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = ast.literal_eval(stringA)
# Result and its type
print("final list", res)
print(type(res))输出
运行以上代码,得到以下结果:
Given string [21,42, 15] final list [21, 42, 15]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP