Python | 使用第二個列表對第一個列表的值進行排序
當需要使用第二個列表對第一個列表的值進行排序時,可以使用“sorted”方法和“zip”方法。
列表可以用來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。
“sorted”方法用於對列表的元素進行排序。
zip 方法接受可迭代物件,將它們聚合為元組,並將其作為結果返回。
以下是演示:
示例
def list_sort(my_list_1, my_list_2):
zipped_list_pairs = zip(my_list_2, my_list_1)
my_result = [x for _, x in sorted(zipped_list_pairs)]
return my_result
my_list_1 = ['m', 'o', 'p', 'l', 'k', 'v', 'c', 'e', 'r']
my_list_2 = [ 1, 0,0, 2, 2, 1, 1, 0,0]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
print("The first list is being sorted based on second list")
print(list_sort(my_list_1, my_list_2))
my_list_3 = ['h', 'k', 'l', 'p', 'q', 'p', 'k', 'l', 'h', 'm', 'u', 'z', 'f', 't']
my_list_4 = [ 0,1,1,1,0,2,2,2,0,2,1,2,1,0]
print("The third list is :")
print(my_list_3)
print("The fourth list is :")
print(my_list_4)
print("The third list is being sorted based on fourth list")
print(list_sort(my_list_3, my_list_4))輸出
The first list is : ['m', 'o', 'p', 'l', 'k', 'v', 'c', 'e', 'r'] The second list is : [1, 0, 0, 2, 2, 1, 1, 0, 0] The first list is being sorted based on second list ['e', 'o', 'p', 'r', 'c', 'm', 'v', 'k', 'l'] The third list is : ['h', 'k', 'l', 'p', 'q', 'p', 'k', 'l', 'h', 'm', 'u', 'z', 'f', 't'] The fourth list is : [0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 1, 2, 1, 0] The third list is being sorted based on fourth list ['h', 'h', 'q', 't', 'f', 'k', 'l', 'p', 'u', 'k', 'l', 'm', 'p', 'z']
解釋
- 定義了一個名為“list_sort”的方法,它接受兩個列表作為引數。
- 它將這兩個列表壓縮並存儲到另一個變數中。
- 對它進行迭代、排序並賦值給另一個變數。
- 然後將其作為結果顯示在控制檯上。
- 定義了兩個列表並在控制檯上顯示。
- 在這些列表上呼叫該方法。
- 然後將其作為輸出顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP