In: Computer Science
create a function that sorted tuple by the second values of each tuple. If the values are the same, sorted by increasing order. Finally returns a list of the first element of each tuple that sorted.
def sort_tup(tup):
#Code here
input : tup1 = [(1, 15), (2, 8), (3, 22), (4, 30), (5, 15)]
output: [4,3,1,5,2]
Code Screenshot :
Executable Code:
#Required function
def sort_tup(tup):
#Empty list
result = []
#Sorting the tuple
sorted_by_second = sorted(tup,key=lambda tup:
tup[1],reverse = True)
for i in sorted_by_second:
#Append elements to the
list
result.append(i[0])
#Return the resultant list
return result
#Testing and Output
tup1 = [(1, 15), (2, 8), (3, 22), (4, 30), (5, 15)]
print("input:",tup1)
print("output:",sort_tup(tup1))
Sample Output :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)