Python – Convert Strings to Character Matrix
Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using List comprehension This is one way in which this task can be performed. In this, we convert the string to list of characters using list() and convert the result to desired matrix.
Python3
test_list = [ 'gfg' , 'is' , 'best' ]
print ( "The original list is : " + str (test_list))
res = [ list (sub) for sub in test_list]
print ( "List String after conversion to Matrix : " + str (res))
|
Output
The original list is : ['gfg', 'is', 'best']
List String after conversion to Matrix : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using loop + list() This is brute force way to perform this task. In this, we run loop and convert each string to character list using list().
Python3
test_list = [ 'gfg' , 'is' , 'best' ]
print ( "The original list is : " + str (test_list))
res = []
for sub in test_list:
res.append( list (sub))
print ( "List String after conversion to Matrix : " + str (res))
|
Output
The original list is : ['gfg', 'is', 'best']
List String after conversion to Matrix : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
Method #3 : Here’s another approach using the map function:
Python3
test_list = [ 'gfg' , 'is' , 'best' ]
print ( "The original list is : " + str (test_list))
res = list ( map ( list , test_list))
print ( "List String after conversion to Matrix : " + str (res))
|
Output
The original list is : ['gfg', 'is', 'best']
List String after conversion to Matrix : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
Time Complexity: O(n) where n is the length of the test_list.
Auxiliary Space: O(n) as we are creating a new list res to store the result.
Explanation: In this approach, we use the map function to apply the list function to each element of the test_list and store the result in the res list.
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...