Python | Delimited String List to String Matrix
Sometimes, while working with Python strings, we can have problem in which we need to convert String list which have strings that are joined by deliminator to String Matrix by separation by deliminator. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + split()
This is one of way in which this task can be performed. In this, we iterate for each string and perform the split using split().
Python3
# Python3 code to demonstrate working of # Delimited String List to String Matrix # Using loop + split() # initializing list test_list = [ 'gfg:is:best' , 'for:all' , 'geeks:and:CS' ] # printing original list print ( "The original list is : " + str (test_list)) # Delimited String List to String Matrix # Using loop + split() res = [] for sub in test_list: res.append(sub.split( ':' )) # printing result print ( "The list after conversion : " + str (res)) |
Output :
The original list is : ['gfg:is:best', 'for:all', 'geeks:and:CS'] The list after conversion : [['gfg', 'is', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Method #2 : Using list comprehension + split()
Yet another way to perform this task, is just modification of above method. In this, we use list comprehension as shorthand and one-liner to perform this.
Python3
# Python3 code to demonstrate working of # Delimited String List to String Matrix # Using list comprehension + split() # initializing list test_list = [ 'gfg:is:best' , 'for:all' , 'geeks:and:CS' ] # printing original list print ( "The original list is : " + str (test_list)) # Delimited String List to String Matrix # Using list comprehension + split() res = [sub.split( ':' ) for sub in test_list] # printing result print ( "The list after conversion : " + str (res)) |
Output :
The original list is : ['gfg:is:best', 'for:all', 'geeks:and:CS'] The list after conversion : [['gfg', 'is', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Please Login to comment...