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

How to Sort a List of Tuples by Their Integer Second Item in Python?

Barbara Streisand
Release: 2024-11-30 14:19:13
Original
942 people have browsed it

How to Sort a List of Tuples by Their Integer Second Item in Python?

Sorting Tuples by Second Item (Integer Value)

Sorting a list of tuples by the second item, an integer value, can be achieved using Python's built-in sorted() function. The key keyword argument allows you to specify a function that retrieves the comparable element from each tuple.

Solution:

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

In this example, lambda x: x[1] is a function that extracts the second item from a tuple. sorted() sorts the list by ascending order of this second item.

Optimization:

For improved performance, you can use operator.itemgetter(1) as the key instead of lambda. itemgetter() is a more optimized way to retrieve a specific item from a tuple.

from operator import itemgetter

sorted_tuples = sorted(
    [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)],
    key=itemgetter(1)
)
Copy after login

The above is the detailed content of How to Sort a List of Tuples by Their Integer Second Item in Python?. 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