Python 字符串列表转换为列表


有时我们可能会遇到包含字符串的数据,但数据流内部的结构是一个 Python 列表。在本文中,我们将学习如何将用字符串括起来的列表转换为实际的 Python 列表,以便进一步进行数据处理。

使用 eval 函数

我们知道 eval 函数会返回作为参数提供的实际结果。因此,我们将给定的字符串提供给 eval 函数,并获取 Python 列表。

示例

 在线演示

stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using eval
res = eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

输出

运行上述代码将得到以下结果:

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

使用 ast.literal_eval 函数

在这种方法中,我们使用 literal_eval 函数,并将字符串作为参数传递给它。它会返回 Python 列表。

示例

 在线演示

import ast
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using literal_eval
res = ast.literal_eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

输出

运行上述代码将得到以下结果:

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

使用 json.loads 函数

loads 函数可以进行类似的转换,其中对字符串进行评估并生成实际的 Python 列表。

示例

 在线演示

import json
stringA = '["Mon", 2,"Tue", 4, "Wed",3]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using loads
res = json.loads(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

输出

运行上述代码将得到以下结果:

Given string :
["Mon", 2,"Tue", 4, "Wed",3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

更新于:2020年6月4日

535 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.