Python - Maximum column values in mixed length 2D List
Last Updated :
17 Apr, 2023
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the maximizations of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw an exception. Let’s discuss certain ways in which this problem can be performed in an error-free manner.
Method #1: Using max() + filter() + map() + list comprehension
The combination of the above three functions combined with list comprehension can help us perform this particular task, the max function helps to perform the maximization, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2.
Python
# Python code to demonstrate
# Maximum column values mixed length 2D List
# using max() + filter() + map() + list comprehension
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is : " + str(test_list))
# using max() + filter() + map() + list comprehension
# Maximum column values mixed length 2D List
res = [max(filter(None, j)) for j in map(None, *test_list)]
# printing result
print("The maximization of columns is : " + str(res))
Output : The original list is : [[1, 5, 3], [4], [9, 8]]
The maximization of columns is : [9, 8, 3]
Time Complexity: O(n*n) where n is the number of elements in the string list. The max() + filter() + map() + list comprehension is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res test_list.
Method #2: Using list comprehension + max() + zip_longest()
If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 0 so that it does not have to handle the void of elements not present.
Python3
# Python3 code to demonstrate
# Maximum column values mixed length 2D List
# using list comprehension + max() + zip_longest()
import itertools
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is : " + str(test_list))
# using list comprehension + max() + zip_longest()
# Maximum column values mixed length 2D List
res = [max(i) for i in itertools.zip_longest(*test_list, fillvalue=0)]
# printing result
print("The maximization of columns is : " + str(res))
Output : The original list is : [[1, 5, 3], [4], [9, 8]]
The maximization of columns is : [9, 8, 3]
Time complexity: O(n*n), where n is the length of the numbers list. The list comprehension + max() + zip_longest() has a time complexity of O(n*n)
Auxiliary Space: O(n),where n is the length of the numbers list.
Method#3: Using Recursive method
Algorithm:
- Define the function max_cols_recursive() that takes a list of lists as input.
- If the input list is empty, return an empty list.
- If the input list has only one list, return that list.
- Initialize an empty list called col_max that will store the maximum values of each column.
- Loop through each column of the input list by using the range of the maximum length of any list in the input list.
- For each column, extract the values of that column by iterating through the sublists of the input list, using 0 as a default value if a sublist does not have a value at the current column index.
- Append the maximum value of that column to col_max.
- Recursively call max_cols_recursive() with a new input list that consists of the tail of each sublist (i.e., all elements except for the first element) of the input list if that sublist has more than one element.
- Return a list that consists of the first element of col_max and the result of the recursive call in step 8.
Python3
def max_cols_recursive(lst):
if not lst:
return []
if len(lst) == 1:
return lst[0]
col_max = []
for i in range(max(map(len, lst))):
col = [sub_lst[i] if i < len(sub_lst) else 0 for sub_lst in lst]
col_max.append(max(col))
return [col_max[0]] + max_cols_recursive([sub_lst[1:] for sub_lst in lst if len(sub_lst) > 1])
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Maximum column values mixed length 2D List
res = max_cols_recursive(test_list)
# printing result
print("The maximization of columns is : " + str(res))
OutputThe original list is : [[1, 5, 3], [4], [9, 8]]
The maximization of columns is : [9, 8, 3]
Time Complexity: O(mn log n)
where m is the maximum length of any list in the input list and n is the length of the input list.
Auxiliary Space: O(mn)
Due to the use of col_max to store the maximum values of each column.
Method #4: Using numpy library
- Import the numpy library: import numpy as np
- Convert the given list of lists to a numpy array using np.array(): arr = np.array(test_list)
- Transpose the array using .T to get the columns as rows: transpose_arr = arr.T
- Apply np.amax() function to get the maximum values for each row: max_values = np.amax(transpose_arr, axis=1)
- Convert the resulting array to a list: max_values_list = max_values.tolist()
- Return the list: return max_values_list
Python3
import numpy as np
def max_cols_numpy(lst):
max_len = max(map(len, lst))
arr = np.full((len(lst), max_len), np.nan)
for i, sublst in enumerate(lst):
arr[i, :len(sublst)] = sublst
max_values = np.nanmax(arr, axis=0)
max_values_list = max_values.tolist()
return max_values_list
# initializing list of lists
test_list = [[1, 5, 3], [4], [9, 8]]
# printing original list
print("The original list is : " + str(test_list))
# Maximum column values mixed length 2D List using numpy
res = max_cols_numpy(test_list)
# printing result
print("The maximization of columns is : " + str(res))
Output:
The original list is : [[1, 5, 3], [4], [9, 8]]
The maximization of columns is : [9.0, 8.0, 3.0]
Time Complexity: O(NM), where N is the number of rows and M is the maximum length of a row.
Space Complexity: O(NM), as we need to store the input list as a numpy array.
Similar Reads
Python - Find maximum length sub-list in a nested list In Python, we often work with nested lists (lists inside lists), and sometimes we need to find out which sub-list has the most items. In this article, we will explore Various methods to Find the maximum length of a sub-list in a nested list. Using max() Function with key=lenThe simplest and most eff
2 min read
Python - Get maximum of Nth column from tuple list Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Letâs discuss certain ways in which this task can be performed. Me
7 min read
Python - Column Maximum in Dictionary Value Matrix Given a Dictionary with Matrix Values, compute maximum of each column of those Matrix. Input : test_dict = {"Gfg" : [[7, 6], [3, 2]], "is" : [[3, 6], [6, 10]], "best" : [[5, 8], [2, 3]]} Output : {'Gfg': [7, 6], 'is': [6, 10], 'best': [5, 8]} Explanation : 7 > 3, 6 > 2, hence ordering. Input :
5 min read
Python | Maximum element in tuple list Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: U
6 min read
Python - Maximum of each Column Sometimes, we are encountered such problems in which we need to find the maximum of each column in a matrix i.e maximum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Letâs discuss certain ways in which this problem can be solved. Method #
4 min read
Python - Ranged Maximum Element in String List Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
4 min read
Min and Max value in list of tuples-Python The task of finding the minimum and maximum values in a list of tuples in Python involves identifying the smallest and largest elements from each position (column) within the tuples. For example, given [(2, 3), (4, 7), (8, 11), (3, 6)], the first elements (2, 4, 8, 3) have a minimum of 2 and a maxim
3 min read
Python - Maximum element in Cropped List Sometimes, while working with Python, we can have a problem in which we need to get maximum of list. But sometimes, we need to get this for between custom indices. This can be need of any domain be it normal programming or web development. Let's discuss certain ways in which this task can be perform
4 min read
Python | Get first element with maximum value in list of tuples In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let's discuss certain ways in which this
4 min read
Python - Maximum element in consecutive subsets We are given a list of numbers and a fixed integer k. The task is to determine the maximum number in every consecutive block of k elements. For instance, consider the list [1,3,2,5,4,6,8,7] with k=3. This list can be divided into consecutive subsets: the first subset is [1,3,2], the next is [3,2,5]
3 min read