排序功能

时间:2020-08-15 06:54:17

标签: python list sorting tuples

list=[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
def st(element):
    return (element[1])
print(sorted(list,key=st))

有人可以解释该程序的工作原理吗?当return语句将5,2,4,3,1返回到已排序的函数时,如何获得已排序的元组列表? 相反,输出不应为[1,2,3,4,5]。因为只有第二个值返回到排序后的函数。

1 个答案:

答案 0 :(得分:1)

sorted函数将使用函数 st()列表(即整个元组)进行排序,以提供排序。 st()函数绝不限制要排序的内容,仅限制用来决定如何排序的内容。

在为sorted函数需要为每个元素回答的问题提供答案时,您可以想到它:确定放置位置时应使用该元素的值是什么?

输出为:

[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

是使用每个元组的第二项决定顺序的排序列表。