How to sort a list of tuples by their first element?

后端 未结 3 867
情歌与酒
情歌与酒 2021-01-11 09:35

I have a list of tuples:

self.gridKeys = self.gridMap.keys() # The keys of the instance of the GridMap (It returns the product of every possible combination          


        
3条回答
  •  渐次进展
    2021-01-11 09:50

    While thefourtheye's solution is correct in the strict sense that it is exactly what you asked for in the title. It may not be actually what you want. It may be better to take it a bit farther via sorting by the reverse of the tuple instead.

    self.gridKeys.sort(key=lambda x:tuple(reversed(x)))
    

    This forces you to have an ordering like:

    [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), ...]
    

    Rather than having the first element be unordered like:

    [(4, 0), (9, 0), (6, 0), (1, 0), (3, 0), ...]
    

    Which is what I get when using:

    self.gridKeys.sort(key=lambda x: x[1])
    

    By default Python does a lexicographical sort from left to right. Reversing the tuple effectively makes Python do the lexicographical sort from right to left.

提交回复
热议问题