Method # 1: Using strip () + split ()
The combination of strip and split function can accomplish a specific task. The strip function can be used to remove parentheses, and the split function can separate the list of data with commas.
# Python3 demo code # to convert a list of strings to a list of list # using strip () + split () # initializing list test_list = [ ’[1, 4, 5]’ , ’[4, 6, 8]’ ] # print original list print ( "The origi nal list is: " + str (test_list)) # using strip () + split () # to convert a list of strings to a list of lists res = [i.strip ( "[]" ). split ( "," ) for i in test_list] # print result print ( "The list after conversion is:" + str (res)) |
Output:
The original list is: [’[1, 4, 5]’, ’[4, 6, 8]’] The list after conversion is: [[’1 ’,’ 4’, ’5’], [’ 4’, ’6’,’ 8’]]
Method # 2: Using a split list and split ()
The task done in the above way can also be done using a slice of the list, in which we split all the elements from the second to the second last element, hence omitting the last parentheses.
# Python3 demo code # to convert a list of strings to a list of list # using list slicing + split () # initializing list < code class = "plain"> test_list = [ ’[1, 4, 5] ’ , ’ [4, 6, 8] ’ ] # print original list print ( "The original list is:" + str (test_list)) # using the list splitting + split () # to transform the list lines to the list of list res = [ i [ 1 : - 1 < code class = "plain">]. split ( ’,’ ) for i in test_list] # print result print ( "The list after conversion is:" + str (res)) |
Output:
The original list is: [’[1, 4, 5]’, ’[4, 6, 8] ’] The list after conversion is: [[’ 1’, ’4’,’ 5’], [’4’,’ 6’, ’8’]]
Python | Convert list of strings to list of list Python functions: Questions
Python | Convert list of strings to list of list String Variables: Questions