Home > Backend Development > Python Tutorial > How to Sort Nested Lists or Tuples by a Specific Element's Index?

How to Sort Nested Lists or Tuples by a Specific Element's Index?

DDD
Release: 2024-12-14 19:36:11
Original
771 people have browsed it

How to Sort Nested Lists or Tuples by a Specific Element's Index?

Sorting Lists or Tuples of Lists or Tuples by an Element at a Specific Index

Consider a list or tuple of lists or tuples with data in a hierarchical structure. For instance:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
Copy after login

To sort this data by the second element of each subset, there are two common approaches: using the sorted() function or the sort() method in ascending order by default.

Using the sorted() function with a key function:

sorted_by_second = sorted(data, key=lambda tup: tup[1])
Copy after login

Using the sort() method with a key function:

data.sort(key=lambda tup: tup[1])  # sorts in place
Copy after login

To sort in descending order, the reverse=True argument can be added:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
Copy after login
data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place
Copy after login

Regardless of whether lists or tuples are used in the original data structure, the key function effectively accesses the desired element at index 1 and performs the sorting accordingly.

The above is the detailed content of How to Sort Nested Lists or Tuples by a Specific Element's Index?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template