当需要借助第二个列表对第一个列表的值进行排序时,将使用“ sorted”方法和“ zip”方法。
列表可用于存储异构值(即,任何数据类型的数据,例如整数,浮点数,字符串等)。
“排序”方法用于对列表中的元素进行排序。
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("第一个列表是:") print(my_list_1) print("第二个列表是:") 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("第三个列表是:") print(my_list_3) print("第四个列表是:") print(my_list_4) print("The third list is being sorted based on fourth list") print(list_sort(my_list_3, my_list_4))输出结果
第一个列表是: ['m', 'o', 'p', 'l', 'k', 'v', 'c', 'e', 'r'] 第二个列表是: [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'] 第三个列表是: ['h', 'k', 'l', 'p', 'q', 'p', 'k', 'l', 'h', 'm', 'u', 'z', 'f', 't'] 第四个列表是: [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”的方法,该方法将两个列表作为参数。
它压缩两个列表并将其存储在另一个变量中。
对其进行迭代,排序并分配给另一个变量。
然后作为结果显示在控制台上
在控制台上定义并显示了两个列表。
在这些列表上调用该方法。
然后将其显示为控制台上的输出。