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
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = [ max ( filter ( None , j)) for j in map ( None , * test_list)]
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
import itertools
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = [ max (i) for i in itertools.zip_longest( * test_list, fillvalue = 0 )]
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 ])
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = max_cols_recursive(test_list)
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(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
test_list = [[ 1 , 5 , 3 ], [ 4 ], [ 9 , 8 ]]
print ( "The original list is : " + str (test_list))
res = max_cols_numpy(test_list)
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...