📜  Python|将字符串列表转换为列表列表

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

Python|将字符串列表转换为列表列表

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

方法 #1:使用strip() + split()
剥离和拆分函数的组合可以执行特定任务。 strip函数可以用来去掉括号,split函数可以使数据列表以逗号分隔。

# Python3 code to demonstrate 
# to convert list of string to list of list
# using strip() + split()
  
# initializing list  
test_list = [ '[1, 4, 5]', '[4, 6, 8]' ]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using strip() + split()
# to convert list of string to list of list
res = [i.strip("[]").split(", ") for i in test_list]
  
# printing result 
print ("The list after conversion is : " +  str(res))

输出 :

The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]

方法 #2:使用列表切片和split()
上述方法中执行的任务也可以使用列表切片来执行,其中我们将所有元素从倒数第二个元素切片,因此省略了最后一个括号。

# Python3 code to demonstrate 
# to convert the list of string to list of list
# using list slicing + split()
  
# initializing list  
test_list = [ '[1, 4, 5]', '[4, 6, 8]' ]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using list slicing + split()
# to convert list of string to list of list
res = [i[1 : -1].split(', ') for i in test_list]
  
# printing result 
print ("The list after conversion is : " +  str(res))

输出 :

The original list is : ['[1, 4, 5]', '[4, 6, 8]']
The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]