Trong bài này, nhiệm vụ sắp xếp tuple (gồm phần tử float) dùng phần tử float. Dùng built-in method sorted() và cách sắp xếp in-place.
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
Bước 1: Cho một list. Bước 2: Sắp xếp dùng sorted(). Bước 3: Sequence (list, tuple, string) hoặc collection (dict, set, frozenset) hoặc iterator cần sắp xếp. Bước 4: Key (tùy chọn) là hàm làm cơ sở so sánh. Bước 5: Nếu Reverse (tùy chọn) là True, sắp xếp giảm dần, mặc định False.
Ví dụ mã
# Mã Python sắp xếp tuple theo phần tử float
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))
Kết quả
Sort of Tuples By Its Float Number :: [('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]