Many times, we come over the dumped data that is found in the string format and we require it to be represented into the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks is quite common in web development. Let’s discuss certain ways in which this can be performed.
Python program that converts a list of strings to a list of lists:
string_list = ["1,2,3", "4,5,6", "7,8,9"] list_of_lists = [] for string in string_list: list_of_lists.append(string.split(",")) print(list_of_lists)
In this program, we start with a list of strings called string_list
. Each string in this list contains comma-separated values. Our goal is to convert each of these strings into a list of integers.
To do this, we first create an empty list called list_of_lists
. We then loop through each string in string_list
using a for
loop. Inside the loop, we use the split()
method to split the string into a list of values using the comma as a delimiter. This gives us a list of strings.
We then append this list of strings to list_of_lists
. After the loop has finished, list_of_lists
contains a list of lists, where each inner list contains the values from one of the original strings in string_list
.
Finally, we print out list_of_lists
to confirm that it contains the expected output:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.