Python - Combine Strings to Matrix
Last Updated :
05 May, 2023
Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split() + zip()
The combination of the above functions can be used to perform this task. In this, we combine strings into Matrix row elements using zip() and split performs the task of extracting words from strings.
Python3
# Python3 code to demonstrate working of
# Combine Strings to Matrix
# Using list comprehension + zip() + split()
# Initializing strings
test_str1 = "Gfg is best"
test_str2 = "1 2 3"
# Printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Combine Strings to Matrix
# Using list comprehension + zip() + split()
res = [[idx, int(j)]
for idx, j in zip(test_str1.split(' '), test_str2.split(' '))]
# Printing result
print("Does Matrix after construction : " + str(res))
Output :
The original list 1 is : ['Gfg', 'is', 'best'] The original list 2 is : [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]] The dictionary after grouping : {'is': [2, 8], 'Gfg': [1, 4, 7], 'best': [1]}
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 #2 : Using map() + split() + zip() The combination of above functions can be used to perform this task. This performs in similar way as above. The difference is that the logic of extension is done using map().
Python3
# Python3 code to demonstrate working of
# Combine Strings to Matrix
# Using map() + zip() + split()
# initializing strings
test_str1 = "Gfg is best"
test_str2 = "1 2 3"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Combine Strings to Matrix
# Using map() + zip() + split()
res = list(map(list, zip(test_str1.split(' '), map(int, test_str2.split(' ')))))
# printing result
print("Does Matrix after construction : " + str(res))
Output :
The original list 1 is : ['Gfg', 'is', 'best'] The original list 2 is : [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]] The dictionary after grouping : {'is': [2, 8], 'Gfg': [1, 4, 7], 'best': [1]}
Method #3: Using for loop and dictionary
Uses a for loop and a dictionary to group the elements in list 2 based on the keys in list 1.
Steps:
- Initialize an empty dictionary, say "result".
- Iterate through each string in list 1, "list1".
- Add a key to "result" dictionary with the current string as key and an empty list as value.
- Iterate through each list in list 2, "list2".
- If the first element of the current list matches with a key in "result" dictionary, then append the second element of the list to the value list of the key.
- Return "result" dictionary.
Python3
def combine_strings_to_matrix_for_loop(list1, list2): # define inputs
result = {} # take empty dictionary
for s in list1: # iterate
result[s] = []
for l in list2:
if l[0] in result:
result[l[0]].append(l[1]) # append values
return result # return result
list1 = ['Gfg', 'is', 'best'] # inputs
list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8]]
print(combine_strings_to_matrix_for_loop(list1, list2)) # print output
Output{'Gfg': [1, 4], 'is': [2, 8], 'best': [1]}
Time Complexity: O(n), where n is the length of the list 2.
Auxiliary Space: O(m), where m is the length of the list 1.
Method #4: Using dictionary comprehension
Steps:
- Define a function called combine_strings_to_matrix_dict_comp that takes in two lists as input: list1 and list2.
- Use dictionary comprehension to create a dictionary where the keys are elements of list1 and the values are lists of elements from list2 whose first element matches the key.
- The values are constructed using a list comprehension that iterates over the elements of list2 and appends the second element of each list whose first element matches the key.
- Return the resulting dictionary.
Python3
def combine_strings_to_matrix_dict_comp(list1, list2):
return {s: [l[1] for l in list2 if l[0] == s] for s in list1}
# Input lists
list1 = ['Gfg', 'is', 'best']
list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8]]
# {'Gfg': [1, 4], 'is': [2, 8], 'best': [1]}
print(combine_strings_to_matrix_dict_comp(list1, list2))
Output{'Gfg': [1, 4], 'is': [2, 8], 'best': [1]}
Time complexity: O(n*m), where n is the length of list1 and m is the length of list2.
Auxiliary space: O(n*m), where n is the length of list1 and m is the length of list2.
Similar Reads
Python - Double Split String to Matrix Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix. Examples: Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = "," Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS
6 min read
Python - Formable Strings Count in Matrix Given strings matrix, the task is to write a Python program to count strings that can be made from letters from the given list. Examples: Input : test_list = [["gfg", "best"], ["all", "love", "gfg"], ["gfg", "is", "good"], ["geeksforgeeks"]], tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"] Outpu
5 min read
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 wh
3 min read
Python Program to Convert Matrix to String Program converts a 2D matrix (list of lists) into a single string, where all the matrix elements are arranged in row-major order. The elements are separated by spaces or any other delimiter, making it easy to represent matrix data as a string.Using List ComprehensionList comprehension provides a con
2 min read
Python - String Matrix Concatenation Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Python | Nth Column vertical string in Matrix Sometimes, while working with Python Matrix, we can have a problem in which we need to access the Matrix in vertical form and extract strings from the same, that too as a string, not merely as a list of characters. This task has its application in gaming in which we need to extract strings during cr
7 min read