Python – 元组中的多列排序
有时,在处理记录时,我们可能会遇到一个问题,即我们需要对其中一列执行排序操作,而在另一列上,如果元素相等,则相反排序。此类问题可能会在许多领域(例如 Web 开发)中作为应用程序出现。让我们讨论一些可以解决这个问题的方法。
Input : test_list = [(6, 7), (6, 5), (6, 4), (7, 10)]
Output : [(7, 10), (6, 4), (6, 5), (6, 7)]
Input : test_list = [(10, 7), (8, 5)]
Output : [(10, 7), (8, 5)]
方法 #1:使用 sorted() + lambda
上述功能的组合可以提供解决这个问题的方法之一。在此,我们使用 sorted() 执行排序,并且顺序和列操作由 lambda函数处理。
Python3
# Python3 code to demonstrate working of
# Multiple Column Sort in Tuples
# Using sorted() + lambda
# initializing list
test_list = [(6, 7), (6, 5), (1, 4), (8, 10)]
# printing original list
print("The original list is : " + str(test_list))
# Multiple Column Sort in Tuples
# Using sorted() + lambda
res = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))
# printing result
print("The sorted records : " + str(res))
Python3
# Python3 code to demonstrate working of
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
from operator import itemgetter
# initializing list
test_list = [(6, 7), (6, 5), (1, 4), (8, 10)]
# printing original list
print("The original list is : " + str(test_list))
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
res = sorted(test_list, key = itemgetter(1))
res = sorted(res, key = itemgetter(0), reverse = True)
# printing result
print("The sorted records : " + str(res))
输出 :
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]
方法 #2:使用 itemgetter() + sorted()
这是可以执行此任务的另一种方式。在此,我们使用 itemgetter() 执行 lambda函数所需的任务。
Python3
# Python3 code to demonstrate working of
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
from operator import itemgetter
# initializing list
test_list = [(6, 7), (6, 5), (1, 4), (8, 10)]
# printing original list
print("The original list is : " + str(test_list))
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
res = sorted(test_list, key = itemgetter(1))
res = sorted(res, key = itemgetter(0), reverse = True)
# printing result
print("The sorted records : " + str(res))
输出 :
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]