使用外部列表對元組進行排序的 Python 程式


如果需要使用外部列表對元組進行排序,可以使用列表解析和‘dict’方法。

以下是對相同內容進行演示:

示例

 演示

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)]

說明

  • 元組列表已定義,並在控制檯上顯示。

  • 定義另一個列表並在控制檯上顯示。

  • 將元組列表轉換成一個字典。

  • 對其進行迭代並將元素儲存在另一個列表中。

  • 這將生成一個有序元組,作為輸出顯示在控制檯上。

更新時間:2021 年 4 月 17 日

269 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.