Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Convert Matrix to Custom Tuple Matrix

Python – Convert Matrix to Custom Tuple Matrix

Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [[4, 5], [7, 3]], add_list = ['Gfg', 'best'] 
Output : [('Gfg', 4), ('Gfg', 5), ('best', 7), ('best', 3)] 

Input : test_list = [[4, 5]], add_list = ['Gfg'] 
Output : [('Gfg', 4), ('Gfg', 5)]

Method #1: Using loop + zip()

The combination of the above further functionalities can be used to solve this problem. In this, we perform the task of binding custom value to each element of the row using g zip(). This is a brute-force way to perform this task.

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
# Using zip() + loop
res = []
for idx, ele in zip(add_list, test_list):
    for e in ele:
        res.append((idx, e))
 
# printing result
print("Matrix after conversion : " + str(res))


Output

The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Time complexity: O(n^2) where n is the size of the input matrix. 
Auxiliary space: O(n^2) as well, because the result list “res” stores n^2 elements, where n is the size of the input matrix.

Method #2: Using list comprehension + zip() 

This is yet another way in which this task can be performed. In this, we perform a similar task as the above method, just as a shorthand. 

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
# Using list comprehension + zip()
res = [(ele1, ele2) for ele1, sub in zip(add_list, test_list) for ele2 in sub]
 
# printing result
print("Matrix after conversion : " + str(res))


Output

The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #3: Using for loop

Python3




# Python3 code to demonstrate working of
# Convert Matrix to Custom Tuple Matrix
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
res = []
for i in range(0, len(add_list)):
    for j in range(0, len(test_list[i])):
        res.append((add_list[i], test_list[i][j]))
 
# printing result
print("Matrix after conversion : " + str(res))


Output

The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Method 4: Using the itertools.chain and zip functions from the itertools module

  1. The convert_to_tuples function takes two inputs, a 2D list test_list and a list add_list.
  2. The itertools.chain.from_iterable function is used to create a flattened 1D list of add_list and test_list.
  3. The zip function is used to create tuples of the form (add_list[i], val) for each item in test_list.
  4. The result is a 1D list of tuples.

Python3




import itertools
 
 
def convert_to_tuples(test_list, add_list):
    return list(zip(itertools.chain.from_iterable([[val] * len(add_list) for val in add_list]), itertools.chain.from_iterable(test_list)))
 
# Main
 
 
def main():
 
    # Input list
    test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
    add_list = ['Gfg', 'is', 'best']
 
    result = convert_to_tuples(test_list, add_list)
    print("Result:", result)
 
 
if __name__ == '__main__':
    main()


Output

Result: [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Time complexity: O(n) where n is the total number of elements in test_list. This is because each element in test_list is processed once.
Auxiliary space: O(n) as well, because the result list contains n tuples, where n is the total number of elements in test_list.

Method #5: Using Numpy and broadcasting

Explanation:

  • First, we import numpy library to use its broadcast_to() and array() functions.
  • Next, we initialize the input lists.
  • We use the broadcast_to() function to expand the add_list array along the rows, so that it becomes a matrix with the same number of rows as test_list and the same number of columns as the length of each sublist of test_list. The [:, None] is used to make sure that the array is broadcasted along the columns.
  • Then, we flatten the resulting array and test_list and use zip() to create the custom tuple matrix.
  • Finally, we print the result.

Python3




import numpy as np
 
# initializing lists
test_list = [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing List elements
add_list = ['Gfg', 'is', 'best']
 
# Convert Matrix to Custom Tuple Matrix
res = np.broadcast_to(
    np.array(add_list)[:, None], (len(add_list), len(test_list[0])))
res = list(zip(res.flatten(), np.array(test_list).flatten()))
 
# printing result
print("Matrix after conversion : " + str(res))


OUTPUT : 
The original list is : [[4, 5, 6], [6, 7, 3], [1, 3, 4]]
Matrix after conversion : [('Gfg', 4), ('Gfg', 5), ('Gfg', 6), ('is', 6), ('is', 7), ('is', 3), ('best', 1), ('best', 3), ('best', 4)]

Time complexity: O(N^2) because it involves two loops, one for iterating over the add_list and another for iterating over the test_list.

Auxiliary space: O(N^2) because we create a numpy array to store the broadcasted add_list and a list to store the resulting custom tuple matrix.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments