📌  相关文章
📜  Python|将列表的字符串表示形式转换为列表

📅  最后修改于: 2022-05-13 01:55:13.969000             🧑  作者: Mango

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

很多时候,我们遇到以字符串格式找到的转储数据,我们要求将其表示为实际找到它的实际列表格式。这种将字符串格式表示的列表转换回列表以执行任务的问题在 Web 开发中很常见。让我们讨论可以执行此操作的某些方式。

方法 #1:使用split()strip()

# Python code to demonstrate converting 
# string representation of list to list
# using strip and split
  
# initializing string representation of a list
ini_list = "[1, 2, 3, 4, 5]"
  
# printing initialized string of list and its type
print ("initial string", ini_list)
print (type(ini_list))
  
# Converting string to list
res = ini_list.strip('][').split(', ')
  
# printing final result and its type
print ("final list", res)
print (type(res))
输出:
initial string [1, 2, 3, 4, 5]

final list ['1', '2', '3', '4', '5']


方法 #2:使用ast.literal_eval()

# Python code to demonstrate converting 
# string representation of list to list
# using ast.literal_eval()
import ast
  
# initializing string representation of a list
ini_list = "[1, 2, 3, 4, 5]"
  
# printing initialized string of list and its type
print ("initial string", ini_list)
print (type(ini_list))
  
# Converting string to list
res = ast.literal_eval(ini_list)
  
# printing final result and its type
print ("final list", res)
print (type(res))
输出:
initial string [1, 2, 3, 4, 5]

final list [1, 2, 3, 4, 5]


方法 #3:使用json.loads()

# Python code to demonstrate converting 
# string representation of list to list
# using json.loads()
import json
  
# initializing string representation of a list
ini_list = "[1, 2, 3, 4, 5]"
  
# printing initialized string of list and its type
print ("initial string", ini_list)
print (type(ini_list))
  
# Converting string to list
res = json.loads(ini_list)
  
# printing final result and its type
print ("final list", res)
print (type(res))
输出:
initial string [1, 2, 3, 4, 5]

final list [1, 2, 3, 4, 5]