Open In App

Python | Sort list of lists by lexicographic value and then length

Improve
Improve
Like Article
Like
Save
Share
Report

There are many times different types of sorting has been discussed in python lists. The sorting of python list of lists has also been discussed. But sometimes, we have two parameters upon which we need to sort. First one being the list sum and next being its length. Let’s discuss how this type of problem can be solved. 

Method #1 : Using sort() twice The first approach that comes into the mind is the generic way that is to use the sort function twice, firstly on basis of the value and then on basis of size of list. 

Python3




# Python code to demonstrate
# sort list of lists by value and length
# using sort() twice
 
# initializing list
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
 
# printing the original list
print ("The original list is : " + str(test_list))
 
# using sort() twice
# sort list of lists by value and length
test_list.sort()
test_list.sort(key = len)
 
# printing result
print ("The list after sorting by value and length " + str(test_list))


Output:

The original list is : [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]] The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Time complexity : O(n^2)
Space complexity : O(n)

  Method #2 : Using lambda function The above method calls a single sort function twice but as an improvement to it, this method calls the sort function just once and uses lambda function to perform both sorts in one go. 

Python3




# Python code to demonstrate
# sort list of lists by value and length
# using lambda function
 
# initializing list
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
 
# printing the original list
print ("The original list is : " + str(test_list))
 
# using lambda function
# sort list of lists by value and length
res = sorted(test_list, key = lambda i: (len(i), i))
 
# printing result
print ("The list after sorting by value and length " + str(res))


Output:

The original list is : [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]] The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Time complexity : O(nlogn)
Space complexity : O(n)

Method #3 : Using  built-in function cmp_to_key from the functools module

Another approach to solve this problem is to use the built-in function cmp_to_key from the functools module. This function allows you to define a comparison function and use it as a key for the sort function.

  • The compare function is a comparison function that takes in two lists and compares them first by their length and then by their elements lexicographically (i.e., in alphabetical order). If the lists are equal, it returns 0.
  • The cmp_to_key function is a function from the functools module that takes in a comparison function and returns a key function that can be used with the sorted function. The key function converts the input into a form that can be compared using the comparison function.
  • The sorted function then sorts the test_list using the key function returned by cmp_to_key and the comparison function compare. The resulting sorted list is then printed.

Here is an example of how to use it:

Python3




from functools import cmp_to_key
 
def compare(x, y):
    # Compare the lengths of the lists first
    if len(x) != len(y):
        return len(x) - len(y)
    # If the lengths are equal, compare the elements lexicographically
    for i in range(len(x)):
        if x[i] != y[i]:
            return x[i] - y[i]
    # If the lists are equal, return 0
    return 0
 
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
 
sorted_list = sorted(test_list, key=cmp_to_key(compare))
 
print(sorted_list)  # prints [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]
#This code is contributed by Edula Vinay Kumar Reddy


Output

[[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Time complexity : O(nm(logn))
Space complexity : O(n)

Method #4: Using numpy.argsort()

This method uses numpy.argsort() function to get the indices of the sorted array along a given axis. The key to sorting by both value and length is to concatenate the values and the length for each list into a single numpy array. Then, we can use numpy.argsort() to get the indices of the sorted array based on the concatenated values and length. Finally, we can use the obtained indices to sort the original list of lists.

Python3




import numpy as np
 
# initializing list
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# using numpy.argsort()
# sort list of lists by value and length
concatenated = np.array([(lst, len(lst)) for lst in test_list], dtype=object)
indices = np.lexsort(concatenated.T)
sorted_list = [test_list[i] for i in indices]
 
# printing result
print("The list after sorting by value and length " + str(sorted_list))


output:
The original list is : [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Time complexity: O(nlogn
Space complexity: O(n)

Method #5: Using the heap sort algorithm.

Step-by-step approach:

  • Define a function to compare two lists based on their lengths and elements lexicographically.
  • Convert the given list of lists into a heap data structure.
  • Extract the minimum element from the heap and add it to the sorted list.
  • Repeat step 3 until the heap is empty.

Python3




import heapq
 
def compare(x, y):
    # Compare the lengths of the lists first
    if len(x) != len(y):
        return len(x) - len(y)
    # If the lengths are equal, compare the elements lexicographically
    for i in range(len(x)):
        if x[i] != y[i]:
            return x[i] - y[i]
    # If the lists are equal, return 0
    return 0
 
def heap_sort(test_list):
    # Convert the list of lists into a heap
    heap = []
    for lst in test_list:
        heapq.heappush(heap, lst)
    # Extract the minimum element from the heap and add it to the sorted list
    sorted_list = []
    while heap:
        sorted_list.append(heapq.heappop(heap))
    return sorted_list
 
test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
sorted_list = heap_sort(test_list)
print(sorted_list) # prints [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]


Output

[[1, 4, 3, 2], [1, 4, 6, 7], [5, 4, 1]]

Time complexity: O(n*logn) 
Auxiliary space: O(n).



Last Updated : 16 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads