Python|根据元素的差异对元组列表进行排序
有时,在处理数据时,我们可能会遇到排序问题。有许多类型的基础可以执行排序。但是本文讨论了基于对的两个元素的差异进行排序。让我们讨论一些可以做到这一点的方法。
方法 #1:使用sorted()
+ lambda
上述功能的组合可以用来解决这个问题。在这种情况下,排序是由sorted()
执行的,并且 lambda函数作为键来执行所需的排序。
# Python3 code to demonstrate working of
# Sort tuple list on basis of difference of elements
# using sorted() + lambda
# initialize list
test_list = [(1, 4), (6, 5), (8, 10)]
# printing original list
print("The original list : " + str(test_list))
# Sort tuple list on basis of difference of elements
# using sorted() + lambda
res = sorted(test_list, key = lambda sub: abs(sub[1] - sub[0]))
# printing result
print("List after sorting by difference : " + str(res))
输出 :
The original list : [(1, 4), (6, 5), (8, 10)]
List after sorting by difference : [(6, 5), (8, 10), (1, 4)]
方法 #2:使用sort() + comparator + cmp()
这是执行此任务的另一种方式。在此,我们传递了sort()
,这是一个比较器函数,它使用cmp()
执行类似的差异逻辑。仅适用于 Python2。
# Python code to demonstrate working of
# Sort tuple list on basis of difference of elements
# using sort() + comparator + cmp()
# comparator function
def diff_sort(ele1, ele2):
return cmp(ele2[0] - ele2[1], ele1[0] - ele1[1])
# initialize list
test_list = [(1, 4), (6, 5), (8, 10)]
# printing original list
print("The original list : " + str(test_list))
# Sort tuple list on basis of difference of elements
# using sort() + comparator + cmp()
test_list.sort(diff_sort)
# printing result
print("List after sorting by difference : " + str(test_list))
输出 :
The original list : [(1, 4), (6, 5), (8, 10)]
List after sorting by difference : [(6, 5), (8, 10), (1, 4)]