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

后端 未结 3 848
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 2021-01-11 09:58

    You can use the key parameter of the sort function, to sort the tuples. The function of key parameter, is to come up with a value which has to be used to compare two objects. So, in your case, if you want the sort to use only the first element in the tuple, you can do something like this

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

    If you want to use only the second element in the tuple, then

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

    sort function will pass each and every element in the list to the lambda function you pass as parameter to key and it will use the value it returns, to compare two objects in the list. So, in your case, lets say you have two items in the list like this

    data = [(1, 3), (1, 2)]
    

    and if you want to sort by the second element, then you would do

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

    First it passes (1, 3) to the lambda function which returns the element at index 1, which is 3 and that will represent this tuple during the comparison. The same way, 2 will be used for the second tuple.

    0 讨论(0)
  • 2021-01-11 09:59

    This should do the trick

    import operator
    self.gridKeys.sort(key=operator.itemgetter(1))
    
    0 讨论(0)
提交回复
热议问题