如何根據內部列表元素對嵌套列表進行排序?

Patricia Arquette
發布: 2024-11-15 08:23:02
原創
847 人瀏覽過

How to Sort a Nested List Based on Inner List Elements?

Sorting Nested Lists Based on Inner List Elements

Nested lists are ubiquitous in programming, and handling them requires adept data manipulation techniques. One such scenario involves sorting the outer list based on specific indices within the inner lists. Fortunately, the following solutions offer effective ways to tackle this challenge:

Using itemgetter

The itemgetter function from the operator module provides a concise solution. It allows you to extract specific elements from each inner list and sort the outer list based on those extracted elements.

from operator import itemgetter

L = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
sorted(L, key=itemgetter(2))
# [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
登入後複製

Using a lambda function

Although slightly less efficient in this simple case, a lambda function can also accomplish the sorting:

sorted(L, key=lambda x: x[2])
# [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
登入後複製

By leveraging itemgetter or a lambda function, you can effectively sort nested lists based on specific indices of their inner elements, thereby enhancing your data processing capabilities.

以上是如何根據內部列表元素對嵌套列表進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板