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

จัดเรียง List of Tuples ตามค่าสุดท้ายของแต่ละ Tuple (เพิ่มขึ้น) ใน Python

จัดเรียงรายการ Tuple ให้เรียงตามค่าสุดท้ายของแต่ละ Tuple จากน้อยไปมาก โดยใช้ Bubble Sort แบบปรับเปลี่ยน

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

def sort_tuple(my_tup):
    my_len = len(my_tup)
    for i in range(0, my_len):
        for j in range(0, my_len-i-1):
            if (my_tup[j][-1] > my_tup[j + 1][-1]):
                temp = my_tup[j]
                my_tup[j] = my_tup[j + 1]
                my_tup[j + 1] = temp
    return my_tup

my_tuple = [(1, 92), (34, 25), (67, 89)]
print("The tuple is :")
print(my_tuple)
print("The sorted list of tuples are : ")
print(sort_tuple(my_tuple))

ผลลัพธ์

The tuple is : [(1, 92), (34, 25), (67, 89)]
The sorted list of tuples are : [(34, 25), (67, 89), (1, 92)]

คำอธิบาย

  • ฟังก์ชัน sort_tuple รับ List of Tuples
  • เปรียบเทียบค่าสุดท้าย [-1] ของ Tuple ติดกัน
  • สลับตำแหน่งถ้าตัวหน้ามากกว่าตัวหลัง (Bubble Sort)
  • คืนค่ารายการที่จัดเรียงแล้ว