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

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

提交回复
热议问题