Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để sắp xếp một bộ theo phần tử float của nó

Trong bài toán này, nhiệm vụ của chúng ta là sắp xếp một bộ tuple (bao gồm các phần tử float) bằng cách sử dụng các phần tử float của nó. Ở đây chúng tôi sử dụng phương thức sorted () có sẵn và cách thực hiện điều này bằng cách sử dụng phương pháp sắp xếp tại chỗ.

Ví dụ

Input:
tuple = [('AAA', '10.265'), ('BBB', '24.107'), ('CCC', '26.541'), ('DDD', '14.256'), ('EEE', '11.365')]
Output:
[('CCC', '26.541'), ('BBB', '24.107'), ('DDD', '14.256'), ('EEE', '11.365'), ('AAA', '10.265')]

Thuật toán

Step 1: Given a list.
Step 2: To sort using sorted ().
Step 3: Sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Step 4: Key(optional) is a function that would serve as a key or a basis of sort comparison.
Step 5: If Reverse (optional) is true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.

Mã mẫu

# Python code to sort a tuples by its float element
def tuplesort(A):
   return(sorted(A, key = lambda x: float(x[1]), reverse = True))
   # Driver Code
   A = [('Adwaita', '19.215'), ('Aadrika', '10.117'), ('Babai', '14.589'), ('Mona', '14.216'), ('Sanj', '8.365')]
print("Sort of Tuples By Its Float Number ::",tuplesort(A))

Đầu ra

Sort of Tuples By Its Float Number :: [('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]