Python – 自定义池排序
给定列表和优先级列表,根据它们在优先级列表中的出现对列表元素进行排序,即出现在 list1 中的元素应该出现在第 1 位,然后出现在其他列表中。
Input : test_list = [5, 6, 3, 7], prio1_list = [6, 3], prio2_list = [5, 7]
Output : [6, 3, 5, 7]
Explanation : 6, 3 occur in p1 list, followed by 5 and 7 which lie in p2 list.
Input : test_list = [5, 6], prio1_list = [6], prio2_list = [5]
Output : [6, 5]
Explanation : 6 occurs in 1st priority list than 5.
方法:使用sort()
+ 比较器键函数
通用 sort() 可用于执行此任务。真正的算法在于传入的比较器函数。适当的返回值及其顺序的分配就是用来解决这个问题的。
# Python3 code to demonstrate working of
# Custom Pool Sorting
# Using sort() + comparator key function
# comparator function
def func(ele):
# Returning 1 or 2 ro assign priority
if ele in prio1_list:
return 1
elif ele in prio2_list:
return 2
# initializing list
test_list = [5, 6, 3, 7, 4, 2, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing priority lists
prio1_list = [4, 6, 3, 8, 10]
prio2_list = [5, 7, 1, 2, 9]
# Using sort() + comparator key function
# key passed with function to manage priority
test_list.sort(key = func)
# printing result
print("List after sorting : " + str(test_list))
输出 :
The original list is : [5, 6, 3, 7, 4, 2, 9, 10]
List after sorting : [6, 3, 4, 10, 5, 7, 2, 9]