Open In App

Python – Combine Strings to Matrix

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:

  1. Initialize an empty dictionary, say “result”.
  2. Iterate through each string in list 1, “list1”.
  3. Add a key to “result” dictionary with the current string as key and an empty list as value.
  4. Iterate through each list in list 2, “list2”.
  5. 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.
  6. 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:

  1. Define a function called combine_strings_to_matrix_dict_comp that takes in two lists as input: list1 and list2.
  2. 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.
  3. 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.
  4. 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. 



Last Updated : 05 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads