Open In App

Python – Maximum column values in mixed length 2D List

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Define the function max_cols_recursive() that takes a list of lists as input.
  2. If the input list is empty, return an empty list.
  3. If the input list has only one list, return that list.
  4. Initialize an empty list called col_max that will store the maximum values of each column.
  5. Loop through each column of the input list by using the range of the maximum length of any list in the input list.
  6. 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.
  7. Append the maximum value of that column to col_max.
  8. 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.
  9. 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))


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

  1. Import the numpy library: import numpy as np
  2. Convert the given list of lists to a numpy array using np.array(): arr = np.array(test_list)
  3. Transpose the array using .T to get the columns as rows: transpose_arr = arr.T
  4. Apply np.amax() function to get the maximum values for each row: max_values = np.amax(transpose_arr, axis=1)
  5. Convert the resulting array to a list: max_values_list = max_values.tolist()
  6. 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads