📜  Python|元组列表中的自定义排序

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

Python|元组列表中的自定义排序

有时,在使用元组列表时,我们可能会遇到需要对其进行排序的问题。朴素排序更容易,但有时,我们必须执行自定义排序,即第一个元素的降序和第二个元素的升序。这些也可以是不同类型的元组的情况。让我们讨论执行这种自定义排序的某些案例和解决方案。

方法 #1:使用sorted() + lambda
可以使用上述功能的组合来执行此任务。在这里,我们只执行普通排序,但另外我们提供了一个 lambda函数来处理上面讨论的自定义排序的情况。

# Python3 code to demonstrate working of
# Custom sorting in list of tuples
# Using sorted() + lambda
  
# Initializing list
test_list = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Custom sorting in list of tuples
# Using sorted() + lambda
res = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))
  
# printing result
print("The tuple after custom sorting is : " + str(res))
输出 :
The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)]
The tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]

方法 #2:使用sorted() + lambda() + sum() (使用元组求和条件)
在这种方法中,类似的解决方案可以维持。但是这里的情况是我们将元组作为元组的第二个元素,并且必须考虑其总和来确定排序顺序。可以在类似的解决方案中扩展除求和之外的其他功能。

# Python3 code to demonstrate working of
# Custom sorting in list of tuples
# Using sorted() + lambda() + sum()
  
# Initializing list
test_list = [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Custom sorting in list of tuples
# Using sorted() + lambda() + sum()
res = sorted(test_list, key = lambda sub: (-sub[0], sum(sub[1])))
  
# printing result
print("The tuple after custom sorting is : " + str(res))
输出 :
The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))]
The tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))]