How does Python sort a list of tuples?

后端 未结 5 1706
广开言路
广开言路 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:49

    No, tuples are sequence types just like strings. They are sorted the same, by comparing each element in turn:

    >>> import random
    >>> sorted([(0,0,0,int(random.getrandbits(4))) for x in xrange(10)])
    [(0, 0, 0, 0), (0, 0, 0, 4), (0, 0, 0, 5), (0, 0, 0, 7), (0, 0, 0, 8),
    (0, 0, 0, 9), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 14)]
    

    The three zeroes are only there to show that something other than the first element must be getting inspected.

提交回复
热议问题