Q:

Python program to sort tuples by total digits

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].

list = [3 ,1,  5, 7]

List of tuples is a list whose each element is a tuple.

tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]

Sorting Tuples by Total Digits

We have a list of tuples with multiple values. And we need to sort the tuples of the list by the total number of digits in the tuple.

Input:
[(2, 4), (12, 40), (1, 23), (43343, 1)]

Output:
[(2, 4), (1, 23), (12, 40), (43343, 1)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

A method to solve the problem is by sorting the list using the sort() method with the sorting key is the sum of lengths of all elements of the tuple.

# Python program to sort tuples 
# by total number of digits in list of tuples 

def digCount(tup):
	return sum([len(str(val)) for val in tup ])

# Creating and Printing tuple list 
tupList = [(43343, 1), (2, 4), (12, 40), (1, 23)]
print("unsorted Tuple list : " + str(tupList))

# sorting list based on digit count using digCount method  
tupList.sort(key = digCount)

# printing result
print("sorted Tuple list : " + str(tupList))

Output:

unsorted Tuple list : [(43343, 1), (2, 4), (12, 40), (1, 23)]
sorted Tuple list : [(2, 4), (1, 23), (12, 40), (43343, 1)]

Method 2:

One method to perform the task is using the lambda function instead of passing a method to the tuple. The lambda will take the list and sort it based on the count of digits in the tuple.

# Python program to sort tuples 
# by total number of digits in list of tuples 

# Creating and Printing tuple list 
tupList = [(43343, 1), (2, 4), (12, 40), (1, 23)]
print("Unsorted Tuple list : " + str(tupList))

# sorting list based on digit count using digCount method  
digitSortedTuple = sorted(tupList, key = lambda tup : sum([len(str(vals)) for vals in tup ]))

# printing result
print("Sorted Tuple list : " + str(digitSortedTuple))

Output:

Unsorted Tuple list : [(43343, 1), (2, 4), (12, 40), (1, 23)]
Sorted Tuple list : [(2, 4), (1, 23), (12, 40), (43343, 1)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now