用最大元素对元组进行排序的Python程序
给定一个元组列表,按元组中的最大元素对元组进行排序。
Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element.
Input : test_list = [(4, 5, 5, 7), (19, 4, 5, 3), (1, 2)]
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 2)]
Explanation : 19 > 7 > 2, is order, hence reverse sorted by maximum element.
方法 #1:使用max() + sort()
在此,我们使用 max() 执行获取元组中最大元素的任务,并使用 sort() 操作执行排序。
Python3
# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using max() + sort()
# helper function
def get_max(sub):
return max(sub)
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
# printing original list
print("The original list is : " + str(test_list))
# sort() is used to get sorted result
# reverse for sorting by max - first element's tuples
test_list.sort(key = get_max, reverse = True)
# printing result
print("Sorted Tuples : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using sort() + lambda + reverse
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
# printing original list
print("The original list is : " + str(test_list))
# lambda function getting maximum elements
# reverse for sorting by max - first element's tuples
test_list.sort(key = lambda sub : max(sub), reverse = True)
# printing result
print("Sorted Tuples : " + str(test_list))
输出:
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
方法 #2:使用 sort() + lambda + reverse
在这里,我们使用类似的功能,唯一的区别是使用 lambda fnc。而不是用于获取反向排序任务的外部函数。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Tuples by Maximum element
# Using sort() + lambda + reverse
# initializing list
test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
# printing original list
print("The original list is : " + str(test_list))
# lambda function getting maximum elements
# reverse for sorting by max - first element's tuples
test_list.sort(key = lambda sub : max(sub), reverse = True)
# printing result
print("Sorted Tuples : " + str(test_list))
输出:
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]