📌  相关文章
📜  Python – 根据自定义排序对单项字典列表进行排序

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

Python – 根据自定义排序对单项字典列表进行排序

给定单项字典列表和键排序列表,根据自定义键执行字典排序。

方法 #1:使用 sorted() + index() + keys() + lambda

上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 进行排序,index() 用于从自定义列表中获取排序,keys() 用于从字典中提取键。

Python3
# Python3 code to demonstrate working of 
# Sort list of Single Item dictionaries according to custom ordering
# Using sorted() + index() + keys() + lambda 
  
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}] 
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# sorted() used to perform sort(), returns the result
# to other variable, ordering handled using index() from order list
res = sorted(test_list1, key = lambda ele: test_list2.index(list(ele.keys())[0]))
  
# printing result 
print("The custom order list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sort list of Single Item dictionaries according to custom ordering
# Using sort() + index() + keys() + lambda
  
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}] 
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# sort() used to perform inplace sort
test_list1.sort(key = lambda ele: test_list2.index(list(ele.keys())[0]))
  
# printing result 
print("The custom order list : " + str(test_list1))


输出

方法 #2:使用 sort() + index() + keys() + lambda

这是可以执行此任务的另一种方式。在此,我们使用 sort() 执行排序任务,执行就地排序,其他结构保持不变。

Python3

# Python3 code to demonstrate working of 
# Sort list of Single Item dictionaries according to custom ordering
# Using sort() + index() + keys() + lambda
  
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}] 
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# sort() used to perform inplace sort
test_list1.sort(key = lambda ele: test_list2.index(list(ele.keys())[0]))
  
# printing result 
print("The custom order list : " + str(test_list1)) 
输出