📌  相关文章
📜  Python|根据其他列表顺序对列表进行排序

📅  最后修改于: 2022-05-13 01:54:44.911000             🧑  作者: Mango

Python|根据其他列表顺序对列表进行排序

排序是大多数编程中使用的基本实用程序,无论是用于竞争性编程还是开发。传统的分拣已经处理过很多次了。这篇特别的文章处理关于其他一些列表元素的排序。
让我们讨论根据其他列表顺序对列表进行排序的某些方法。
方法#1:使用列表推导
列表推导可用于完成此特定任务。在此,我们只需检查列表 2 中的每个元素是否与当前元组匹配,并以排序方式相应地追加。

Python3
# Python3 code to demonstrate
# to sort according to other list
# using list comprehension
 
# initializing list of tuples
test_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = ['d', 'c', 'a', 'b']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing sort order list
print ("The sort order list is : " + str(sort_order))
 
# using list comprehension
# to sort according to other list
res = [tuple for x in sort_order for tuple in test_list if tuple[0] == x]
 
# printing result
print ("The sorted list is : " + str(res))


Python3
# Python code to demonstrate
# to sort according to other list
# using sort() + lambda + index()
 
# initializing list of tuples
test_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = ['d', 'c', 'a', 'b']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing sort order list
print ("The sort order list is : " + str(sort_order))
 
# using sort() + lambda + index()
# to sort according to other list
# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2
test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3
 
# printing result
print ("The sorted list is : " + str(test_list))


输出:
The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]


方法 #2:使用 sort() + lambda + index()
执行此特定操作的简写,排序函数可以与带有键的 lambda 一起使用,以指定每对元组的函数执行,并使用索引函数维护其他列表的列表顺序。

Python3

# Python code to demonstrate
# to sort according to other list
# using sort() + lambda + index()
 
# initializing list of tuples
test_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
# initializing sort order
sort_order = ['d', 'c', 'a', 'b']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# printing sort order list
print ("The sort order list is : " + str(sort_order))
 
# using sort() + lambda + index()
# to sort according to other list
# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2
test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3
 
# printing result
print ("The sorted list is : " + str(test_list))
输出:
The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]