How does Python sort a list of tuples?

后端 未结 5 1710
广开言路
广开言路 2020-12-08 18:33

Empirically, it seems that Python\'s default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what\'s the ri

5条回答
  •  庸人自扰
    2020-12-08 18:56

    It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.

提交回复
热议问题