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

โปรแกรม Python เรียง List of Tuples ตามตัวอักษร

Sort List of Tuples Alphabetically ใน Python

เมื่อต้องการเรียง List of Tuples ตามตัวอักษร (Alphabetical Order) ใช้เมธอด sort() ซึ่งทำ In-place Sorting (เปลี่ยน List ตัวเอง)

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

def sort_tuple_vals(my_tup):
    # เรียงตาม Element Index 0 (ตัวแรกของแต่ละ Tuple)
    my_tup.sort(key=lambda x: x[0])
    return my_tup

my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56), ("Nysa", 35), ("May", "Pink")]
print("The tuple is ")
print(my_tup)

print("After sorting the tuple alphabetically, it becomes : ")
print(sort_tuple_vals(my_tup))

ผลลัพธ์

The tuple is [('Hey', 18), ('Jane', 33), ('Will', 56), ('Nysa', 35), ('May', 'Pink')]
After sorting the tuple alphabetically, it becomes : [('Hey', 18), ('Jane', 33), ('May', 'Pink'), ('Nysa', 35), ('Will', 56)]

คำอธิบาย

  • Define Function sort_tuple_vals รับ Tuple List
  • ใช้ sort(key=lambda x: x[0]) เรียงตาม Index 0 (String)
  • In-place: List ตัวเดิมถูกเปลี่ยน
  • Return List ที่เรียงแล้ว
  • เรียก Function และแสดงผล

ลำดับ Alphabetical

BeforeAfter
HeyHey
JaneJane
WillMay
NysaNysa
MayWill

ลำดับ: H (Hey) < J (Jane) < M (May) < N (Nysa) < W (Will)

sorted() vs sort()

# sort() - In-place, คืน None
my_tup.sort(key=lambda x: x[0])
print(my_tup)  # เปลี่ยนไปแล้ว

# sorted() - คืน List ใหม่, ตัวเดิมไม่เปลี่ยน
my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56)]
new_list = sorted(my_tup, key=lambda x: x[0])
print(my_tup)    # Original ไม่เปลี่ยน
print(new_list)  # เรียงแล้ว

เรียงตาม Column อื่น

# เรียงตาม Index 1 (ตัวเลข)
my_tup = [("Hey", 18), ("Jane", 33), ("Will", 56), ("Nysa", 35), ("May", 20)]
my_tup.sort(key=lambda x: x[1])
print(my_tup)  # [('Hey', 18), ('May', 20), ('Jane', 33), ('Nysa', 35), ('Will', 56)]

# เรียงหลาย Key (Primary: Index 1, Secondary: Index 0)
my_tup.sort(key=lambda x: (x[1], x[0]))

Descending Order (มากไปน้อย / Z-A)

# เรียง Key ตาม Alphabet ใหญ่ไปเล็ก
my_tup.sort(key=lambda x: x[0], reverse=True)
print(my_tup)  # [('Will', 56), ('Nysa', 35), ('May', 'Pink'), ('Jane', 33), ('Hey', 18)]

# เรียง Value มากไปน้อย
my_tup.sort(key=lambda x: x[1], reverse=True)

Case-Insensitive Sort

my_tup = [("hey", 18), ("Jane", 33), ("Will", 56)]
my_tup.sort(key=lambda x: x[0].lower())
print(my_tup)  # [('hey', 18), ('Jane', 33), ('Will', 56)]