Python - 按其他列表顺序重新排列列表
有时,在使用Python列表时,我们可能会遇到需要根据其他列表排序执行列表排序的问题。这可以应用于许多领域,包括日间编程和学校编程。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
可以使用列表推导来执行此任务。在此,我们迭代排序顺序列表,如果列表存在于目标列表中,则简单地追加。索引与排序顺序列表相似。
# Python3 code to demonstrate working of
# Rearrange list by other list order
# Using list comprehension
# initializing lists
test_list1 = [5, 6, 7, 4, 8, 9, 2]
test_list2 = [9, 6, 4]
# printing original list
print("The original list 1 is : " + str(test_list1))
# printing original list
print("The original list 2 is : " + str(test_list2))
# Rearrange list by other list order
# Using list comprehension
res = [ele for ele in test_list1 if ele in test_list2]
# printing result
print("The list after sorting is : " + str(res))
输出 :
The original list 1 is : [5, 6, 7, 4, 8, 9, 2]
The original list 2 is : [9, 6, 4]
The list after sorting is : [6, 4, 9]
方法 #2:使用 sorted + index()
上述功能的组合也可用于执行此任务。在此我们使用以索引为键的排序函数根据其他列表进行排序。
# Python3 code to demonstrate working of
# Rearrange list by other list order
# Using sorted + index()
# initializing lists
test_list1 = [5, 6, 7, 4, 8, 9, 2]
test_list2 = [9, 6, 4]
# printing original list
print("The original list 1 is : " + str(test_list1))
# printing original list
print("The original list 2 is : " + str(test_list2))
# Rearrange list by other list order
# Using sorted + index()
res = sorted(test_list2, key = test_list1.index)
# printing result
print("The list after sorting is : " + str(res))
输出 :
The original list 1 is : [5, 6, 7, 4, 8, 9, 2]
The original list 2 is : [9, 6, 4]
The list after sorting is : [6, 4, 9]