เมื่อพิจารณาถึง tuple หน้าที่ของเราคือจัดเรียงรายการของ tuple ตามลำดับที่เพิ่มขึ้นตามคีย์ใดๆ ใน tuple เราจำเป็นต้องจัดเรียงตามคีย์ที่ระบุ เพื่อทำสิ่งนี้ที่นี่ เราใช้ฟังก์ชัน sorted() ซึ่งเราจัดเรียงโดยใช้ key=last และเก็บรายการสุดท้ายเป็นดัชนีคีย์ตามที่เราต้องเรียงลำดับ tuples ที่กำหนด
ตัวอย่าง
Input: A = [(2, 55), (1, 20), (4, 40), (2, 30)]
k = 0
Output: [(1, 20), (2, 30), (2, 55), (4, 40)]
คำอธิบาย
การเพิ่มการเรียงลำดับโดยใช้คีย์ดัชนีที่ 0
อัลกอริทึม
Step 1: get the last key value. Step 2: next we use inbuilt function sorted () method where we sort them using key=last and store last as the key index according to which we have to sort the given tuples. Step 3: display sorted list.
โค้ดตัวอย่าง
# Python program to sort a list of tuples
# in increasing order by any key
# get the last key.
def data(n):
return n[k]
# function to sort the tuple
def tuplesort(tup):
# We pass used defined function last
# As a parameter.
return sorted(tup, key = data)
# Driver code
a = [(230, 456, 120), (205, 414, 39), (89, 410, 213)]
k = int(input("Enter the Index ::>"))
print("Sorted:"),
print(tuplesort(a))
ผลลัพธ์
Enter the Index ::>2 Sorted: [(205, 414, 39), (230, 456, 120), (89, 410, 213)]