Home > Article > Backend Development > Sorting method when python list elements are tuples
The following is a sorting method for everyone to share a python list element when it is a tuple. It has a good reference value and I hope it will be helpful to everyone. Come and take a look together
As shown below:
dist = [('m',5),('e',4),('c',9),('d',1)] dist.sort(key= operator.itemgetter(0)) print(dist) dist = [('m',5),('e',4),('c',9),('d',1)] dist.sort(key= lambda k:k[0]) print(dist)
① When key=operator.itemgetter(0), the first element of the tuple is taken for comparison.
② When key=operator.itemgetter(1), the second element of the tuple is taken for comparison.
key=lamda k:k[0 or 1] Similarly
Related recommendations:
Python List intersection, union, difference set Application
Detailed explanation of two example methods of python list sorting
The above is the detailed content of Sorting method when python list elements are tuples. For more information, please follow other related articles on the PHP Chinese website!