Python sorted ()ฟังก์ชั่น
ตัวอย่าง
เรียงลำดับทูเพิล:
a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)
ความหมายและการใช้งาน
ฟังก์ชันsorted()
ส่งคืนรายการที่เรียงลำดับของอ็อบเจ็กต์ iterable ที่ระบุ
คุณสามารถระบุลำดับจากน้อยไปมากหรือมากไปหาน้อย สตริงจะถูกจัดเรียงตามตัวอักษร และตัวเลขจะถูกจัดเรียงตามตัวเลข
หมายเหตุ:คุณไม่สามารถเรียงลำดับรายการที่มีทั้งค่าสตริงและค่าตัวเลขได้
ไวยากรณ์
sorted(iterable, key=key, reverse=reverse)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
iterable | Required. The sequence to sort, list, dictionary, tuple etc. |
key | Optional. A Function to execute to decide the order. Default is None |
reverse | Optional. A Boolean. False will sort ascending, True will sort descending. Default is False |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
เรียงลำดับตัวเลข:
a = (1,
11, 2)
x = sorted(a)
print(x)
ตัวอย่าง
เรียงลำดับจากน้อยไปมาก:
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
ตัวอย่าง
เรียงลำดับจากมากไปน้อย:
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a,
reverse=True)
print(x)