Open In App

Python | String List to Column Character Matrix

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we need to convert the string list to Character Matrix where each row is String list column. This can have possible application in data domains. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension This is one of the way in which this task can be performed. In this, we iterate for each String element and construct rows using index elements. 

Python3




# Python3 code to demonstrate working of
# String List to Column Character Matrix
# Using list comprehension
 
# initializing list
test_list = ["123", "456", "789"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# String List to Column Character Matrix
# Using list comprehension
res = [[sub[idx] for sub in test_list] for idx in range(len(test_list[0]))]
 
# printing result
print("The Character Matrix : " + str(res))


Output : 

The original list is : ['123', '456', '789']
The Character Matrix : [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]

Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements

  Method #2 : Using zip() + map() The combination of above functions can be used to perform this task. In this, we construct the columns using zip() and map() is used to compile all the nested lists. 

Python3




# Python3 code to demonstrate working of
# String List to Column Character Matrix
# Using zip() + map()
 
# initializing list
test_list = ["123", "456", "789"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# String List to Column Character Matrix
# Using zip() + map()
res = list(map(list, zip(*test_list)))
 
# printing result
print("The Character Matrix : " + str(res))


Output : 

The original list is : ['123', '456', '789']
The Character Matrix : [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]

Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.

Method #3 : Using nested loops

Approach

we use nested loops to iterate over each character in the strings of the input list. We create a new list of lists, where each inner list represents a column in the final matrix. We use range(len(string_list[0])) to iterate over the length of the first string in the input list, assuming that all strings have the same length. Then, for each index i, we iterate over each string in the input list and append the ith character to a new column list. Finally, we append the column list to the char_matrix list.

Algorithm

1. Initialize an empty list called char_matrix.
2. Iterate from i=0 to len(string_list[0])-1.
3. Initialize an empty list called column.
4. Iterate through each string in string_list.
5. Append the i-th character of the current string to the column list.
6. Append the column list to the char_matrix list.
7. Return char_matrix.

Python3




# Sample list
string_list = ['123', '456', '789']##give input
 
# Using nested loops
char_matrix = []
for i in range(len(string_list[0])):
    column = []
    for string in string_list:
        column.append(string[i])#append it to column
    char_matrix.append(column)#append them to char matrix
print(char_matrix)#print column matrix


Output

[['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]

Time Complexity: O(len(string_list)*len(string_list[0])), The outer loop runs len(string_list[0]) times. The inner loop runs len(string_list) times for each iteration of the outer loop. The append operation takes constant time.

Auxiliary Space: O(len(string_list)*len(string_list[0])), We are creating a new list of lists called char_matrix to store the character matrix. The size of char_matrix will be len(string_list[0]) by len(string_list).

Method 4 :  Use the itertools library. 

steps

Import the itertools library.
Initialize the test_list with the given values.
Use the itertools.zip_longest() function to combine the characters from each string into tuples. This function will return an iterator that produces tuples containing the characters from each string, padded with None if necessary to make all the tuples the same length.
Use a list comprehension to convert the tuples into lists.
Use the itertools.chain() function to combine the lists into a single list.
Use the list() function to convert the chain object into a list.
Use the itertools.zip_longest() function again to group the characters into sublists of length equal to the number of strings in the input list.
Use a list comprehension to remove the None values from each sublist.
Print the resulting list of lists.
 

Python3




import itertools
 
# initializing list
test_list = ["123", "456", "789"]
 
# Using itertools.zip_longest() and list comprehension
res = [list(filter(lambda x: x is not None, lst)) for lst in itertools.zip_longest(*test_list)]
 
# printing result
print("The Character Matrix : ", res)


Output

The Character Matrix :  [['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9']]

Time complexity: O(NM), where N is the number of strings in the input list and M is the maximum length of the strings.
Auxiliary space: O(NM), since we are creating multiple lists and iterators.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads