Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python เรียงลำดับ Tuple ตามค่า float


เรียงลำดับลิสต์ของ tuple ตามอิลิเมนต์ที่ 2 ซึ่งเป็นสตริงแทน float ใช้ sorted() พร้อม key function

ตัวอย่าง

Input: [('AAA','10.265'), ('BBB','24.107'), ('CCC','26.541'), ('DDD','14.256'), ('EEE','11.365')]
Output: เรียงจากมากไปน้อย: [('CCC','26.541'), ('BBB','24.107'), ...]

อัลกอริทึม

  1. ใช้ sorted(A, key=lambda x: float(x[1]), reverse=True)
  2. key แปลงสตริงเป็น float
  3. reverse=True เรียงมากไปน้อย

โค้ดตัวอย่าง

def tuplesort(A):
    return sorted(A, key=lambda x: float(x[1]), reverse=True)

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))

ผลลัพธ์

[('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]