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