เมื่อจำเป็นต้องสั่งซื้อ tuples โดยใช้รายการภายนอก สามารถใช้ list comprehension และ 'dict' method ได้
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
my_list = [('Mark', 34), ('Will', 91), ('Rob', 23)]
print("The list of tuple is : ")
print(my_list)
ordered_list = ['Will', 'Mark', 'Rob']
print("The ordered list is :")
print(ordered_list)
temp = dict(my_list)
my_result = [(key, temp[key]) for key in ordered_list]
print("The ordered tuple list is : ")
print(my_result) ผลลัพธ์
The list of tuple is :
[('Mark', 34), ('Will', 91), ('Rob', 23)]
The ordered list is :
['Will', 'Mark', 'Rob']
The ordered tuple list is :
[('Will', 91), ('Mark', 34), ('Rob', 23)] คำอธิบาย
-
รายการ tuple ถูกกำหนดและแสดงบนคอนโซล
-
มีการกำหนดรายการอื่นและแสดงบนคอนโซล
-
รายการทูเพิลจะถูกแปลงเป็นพจนานุกรม
-
มีการทำซ้ำและองค์ประกอบจะถูกเก็บไว้ในรายการอื่น
-
ซึ่งส่งผลให้มีทูเพิลที่เรียงลำดับซึ่งแสดงเป็นเอาต์พุตบนคอนโซล