Python|将给定列表转换为嵌套列表
有时,我们在列表中遇到字符串格式的数据,需要将其转换为列表的列表。这种将字符串列表转换为嵌套列表的问题在 Web 开发中很常见。让我们讨论可以执行此操作的某些方式。
方法#1:使用迭代
# Python code to convert list
# of string into list of list
# List initialization
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
'Geeks, 123', '555.7492, 152.5406']
temp = []
# Getting elem in list of list format
for elem in Input:
temp2 = elem.split(', ')
temp.append((temp2))
# List initialization
Output = []
# Using Iteration to convert
# element into list of list
for elem in temp:
temp3 = []
for elem2 in elem:
temp3.append(elem2)
Output.append(temp3)
# printing
print(Output)
输出:
[[‘Geeeks’, ‘Forgeeks’], [‘65.7492’, ‘62.5405’], [‘Geeks’, ‘123’], [‘555.7492’, ‘152.5406’]]
方法#2:使用ast
[list with numeric values]
# Python code to convert list
# of string into list of list
# importing
import ast
# List Initialization
Input = ['12, 454', '15.72, 82.85', '52.236, 25256', '95.9492, 72.906']
# using ast to convert
Output = [list(ast.literal_eval(x)) for x in Input]
# printing
print(Output)
输出:
[[12, 454], [15.72, 82.85], [52.236, 25256], [95.9492, 72.906]]