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
test_list = [[ 4 , 5 , 6 ], [ 6 , 7 , 3 ], [ 1 , 3 , 4 ]]
print ( "The original list is : " + str (test_list))
add_list = [ 'Gfg' , 'is' , 'best' ]
res = []
for idx, ele in zip (add_list, test_list):
for e in ele:
res.append((idx, e))
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
test_list = [[ 4 , 5 , 6 ], [ 6 , 7 , 3 ], [ 1 , 3 , 4 ]]
print ( "The original list is : " + str (test_list))
add_list = [ 'Gfg' , 'is' , 'best' ]
res = [(ele1, ele2) for ele1, sub in zip (add_list, test_list) for ele2 in sub]
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
test_list = [[ 4 , 5 , 6 ], [ 6 , 7 , 3 ], [ 1 , 3 , 4 ]]
print ( "The original list is : " + str (test_list))
add_list = [ 'Gfg' , 'is' , 'best' ]
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]))
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
- The convert_to_tuples function takes two inputs, a 2D list test_list and a list add_list.
- The itertools.chain.from_iterable function is used to create a flattened 1D list of add_list and test_list.
- The zip function is used to create tuples of the form (add_list[i], val) for each item in test_list.
- 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)))
def main():
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
test_list = [[ 4 , 5 , 6 ], [ 6 , 7 , 3 ], [ 1 , 3 , 4 ]]
print ( "The original list is : " + str (test_list))
add_list = [ 'Gfg' , 'is' , 'best' ]
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()))
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.
Please Login to comment...