Python - Convert Matrix to overlapping Tuple Pairs
Last Updated : 02 May, 2023
Sometimes, while working with Python data, we can have a problem in which we need to perform overlap of elements in Matrix, and convert them as tuple pairs. This kind of problem can occur in various application in data domain. Let's discuss certain ways in which this task can be performed.
Input : test_list = [[5, 6, 3], [8, 6, 2], [2, 5, 1]]
Output : [(5, 6), (6, 3), (8, 6), (6, 2), (2, 5), (5, 1)]
Input : test_list = [[5, 6, 3]]
Output : [(5, 6), (6, 3)]
Method #1: Using loop This is brute force way in which this task can be performed. In this, we iterate each list and extract consecutive elements and add them as pair in result list.
Python3 # Python3 code to demonstrate working of # Convert Matrix to overlapping Tuple Pairs # Using loop # initializing list test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]] # printing original list print("The original list is : " + str(test_list)) # Convert Matrix to overlapping Tuple Pairs # Using loop res = [] for sub in test_list: res.append((sub[0], sub[1])) res.append((sub[1], sub[2])) # printing result print("Filtered tuples : " + str(res))
Output : The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n), where n is the total number of elements in the matrix.
Auxiliary Space: O(n), where n is the total number of elements in the matrix. This is because the output list 'res' will contain n/2 pairs of elements.
Method #2: Using loop + list slicing The combination of above functionalities can be used to solve this problem. This offers flexibility to extend logic to more custom tuple sizes, more than 2 as well.
Python3 # Python3 code to demonstrate working of # Convert Matrix to overlapping Tuple Pairs # Using loop + list slicing # initializing list test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]] # printing original list print("The original list is : " + str(test_list)) # Convert Matrix to overlapping Tuple Pairs # Using loop + list slicing res = [] for sub in test_list: for idx in range(len(sub) -1): res.append(tuple(sub[idx:idx + 2])) # printing result print("Filtered tuples : " + str(res))
Output : The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n^2), where n is the length of the longest sublist in the matrix.
Auxiliary space: O(n^2), where n is the length of the longest sublist in the matrix.
Method 3 : use list comprehension and the zip() function
- Create a list called "test_list" containing three sublists.
- Use list comprehension and zip() to create a new list called "res".
- The first part of the list comprehension, "for sub in test_list", iterates through each sublist in "test_list".
- The second part of the list comprehension, "for pair in zip(sub, sub[1:])", iterates through each tuple in the result of "zip(sub, sub[1:])". "zip(sub, sub[1:])" creates a list of tuples where the first element in each tuple is an element from "sub" and the second element in each tuple is the following element in "sub".
- The result of the list comprehension, "tuple(pair)", creates a new tuple for each pair of elements in "sub".
- This tuple contains the first and second elements of the pair.
- The "res" list is now a list of tuples containing every pair of adjacent elements from each sublist in "test_list".
- The "print" statement outputs the filtered tuples in "res" as a string.
Python3 test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]] # using list comprehension and zip() res = [tuple(pair) for sub in test_list for pair in zip(sub, sub[1:])] # printing result print("Filtered tuples: " + str(res))
OutputFiltered tuples: [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity:O(n^2), where n is the total number of elements in the matrix.
Auxiliary space: O(n^2) because the resulting list contains n^2/2 tuples.
Method #4: Using NumPy Library
- Import the NumPy library.
- Convert the input matrix to a NumPy array using the numpy.array() function.
- Use the numpy.lib.stride_tricks.as_strided() function to create a view of the array with overlapping windows. The window size is (2,2) since we want to create tuples of length 2.
- Use the numpy.ravel() function to flatten the overlapping windows view into a 1D array.
- Convert the 1D array into a list of tuples using the zip() function.
- Print the resulting list of tuples.
Python3 import numpy as np # initializing list test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]] # printing original list print("The original list is : " + str(test_list)) # Convert Matrix to overlapping Tuple Pairs # Using NumPy Library arr = np.array(test_list) view = np.lib.stride_tricks.as_strided(arr, shape=(arr.shape[0], arr.shape[1]-1, 2), strides=(arr.strides[0], arr.strides[1], arr.strides[1])) flat_view = np.ravel(view) res = list(zip(flat_view[::2], flat_view[1::2])) # printing result print("Filtered tuples : " + str(res))
Output:
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]] Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
Time complexity: O(n^2) where n is the length of the input list.
Auxiliary space: O(n) since we create a new array with overlapping windows view, and then flatten it to a 1D array.
Similar Reads
Python | Conversion to N*N tuple matrix Sometimes, while working with data, we can have a problem in which we have data in form of tuple Matrix with uneven length rows. In this case there's a requirement to complete the N*N matrix with a default value. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop
5 min read
Convert List to Tuple in Python The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
2 min read
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
6 min read
Convert List of Dictionary to Tuple list Python Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read
Python Program to Convert Tuple Matrix to Tuple List Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 min read
Python - Convert Tuple to Tuple Pair Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which thi
10 min read