Home  >  Article  >  Backend Development  >  Sorting method when python list elements are tuples

Sorting method when python list elements are tuples

不言
不言Original
2018-04-18 10:52:372447browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn