📜  Python|按元组的第 N 个元素对元组列表进行排序

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

Python|按元组的第 N 个元素对元组列表进行排序

有时,在使用Python列表时,我们可能会遇到需要根据任何元组元素对列表进行排序的问题。这些必须是按特定元组索引执行排序的通用方式。这在 Web 开发领域具有很好的实用性。让我们讨论可以执行此任务的某些方式。

方法 #1:使用sort() + lambda
上述功能的组合可用于执行此任务。在这种情况下,我们只需将 lambda函数传递给sort() ,并根据必须执行的排序具有适当的元组元素索引。

# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sort() + lambda
  
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# index according to which sort to perform
N = 1
  
# Sort tuple list by Nth element of tuple
# using sort() + lambda
test_list.sort(key = lambda x: x[N])
  
# printing result 
print("List after sorting tuple by Nth index sort : " + str(test_list))
输出 :
The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]

方法 #2:使用sort() + itemgetter()
这与上述方法类似。不同之处在于我们使用itemgetter()来执行上述方法中由 lambda 完成的任务。

# Python3 code to demonstrate working of
# Sort tuple list by Nth element of tuple
# using sort() + itemgetter()
from operator import itemgetter
  
# initializing list
test_list = [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# index according to which sort to perform
N = 1
  
# Sort tuple list by Nth element of tuple
# using sort() + itemgetter()
test_list.sort(key = itemgetter(N))
  
# printing result 
print("List after sorting tuple by Nth index sort : " + str(test_list))
输出 :
The original list is : [(4, 5, 1), (6, 1, 5), (7, 4, 2), (6, 2, 4)]
List after sorting tuple by Nth index sort : [(6, 1, 5), (6, 2, 4), (7, 4, 2), (4, 5, 1)]