Home > Backend Development > Python Tutorial > How to Sort a List of Tuples by Their Integer Values?

How to Sort a List of Tuples by Their Integer Values?

Linda Hamilton
Release: 2024-12-02 18:31:15
Original
819 people have browsed it

How to Sort a List of Tuples by Their Integer Values?

Sorting a List of Tuples by Second Item (Integer Value)

You have provided a list of tuples in the format [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)]. You seek to sort this list in ascending order based on the integer values within the tuples.

To achieve this sorting, leverage the key keyword argument in the sorted() function. By default, it sorts in increasing order. Here's the solution:

sorted([('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], key=lambda x: x[1])
Copy after login

The key parameter accepts a function that retrieves the comparable element from your data structure. In this case, it is the second element of the tuple, so we reference it as x[1].

For improved performance, consider using operator.itemgetter(1) as suggested by jamylak. It is essentially a faster version of lambda x: x[1].

The above is the detailed content of How to Sort a List of Tuples by Their Integer Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template