📌  相关文章
📜  Python|按特定顺序对元组列表进行排序

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

Python|按特定顺序对元组列表进行排序

元组的正常排序之前已经处理过。本文旨在根据某些列表中提供的顺序,按第二个元素对给定的元组列表进行排序。

方法 #1:使用列表理解 + filter() + lambda
以上三个函数可以结合起来执行列表推导执行迭代的特定任务,lambda函数用作过滤以根据元组的第二个元素进行排序的辅助函数。

# Python3 code to demonstrate
# sort list of tuples according to second
# using list comprehension + filter() + lambda
  
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
  
# initializing sort order 
sort_order = [4, 2, 3]
  
# printing the 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 + filter() + lambda
# sort list of tuples according to second
res = [i for j in sort_order 
      for i in filter(lambda k: k[1] == j, test_list)]
  
# printing result
print ("The list after appropriate sorting : " + str(res))
输出:
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]


方法 #2:使用sorted() + index() + lambda
sorted函数可用于根据指定的顺序进行排序。 index函数指定必须考虑元组的第二个元素,并在 lambda 的帮助下将所有元素连接起来。

# Python3 code to demonstrate
# sort list of tuples according to second
# using sorted() + index() + lambda
  
# initializing list of tuples
test_list = [('a', 2), ('c', 3), ('d', 4)]
  
# initializing sort order 
sort_order = [4, 2, 3]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# printing sort order list 
print ("The sort order list is : " + str(sort_order))
  
# using sorted() + index() + lambda
# sort list of tuples according to second
res = list(sorted(test_list, 
      key = lambda i: sort_order.index(i[1])))
  
# printing result
print ("The list after appropriate sorting : " + str(res))
输出:
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]