在 Python 中根据每个子列表的第一个元素对列表进行排序

在 Python 中,根据每个子列表的第一个元素对“列表的列表”进行排序是一项常见的任务。无论你是处理数据点、坐标还是任何其他结构化信息,根据其第一个元素的值来排列列表都可能至关重要。在本文中,我们将探讨如何根据每个子列表的第一个元素对列表进行排序。这个过程会根据子列表中第一个元素的值来组织外层列表。这里,我们将探索实现这一任务的不同方法。

以下是我们可以在 Python中根据每个子列表的第一个元素对列表进行排序的几种方法:

  • 使用带有 Lambda 函数的 sorted 函数
  • 使用带有自定义比较器的 sort() 方法
  • 结合 Sorted 使用列表推导式
  • 使用 INLINECODEda065261 模块中的 INLINECODEfc729ac7 函数
  • 使用自定义函数

使用 sorted() 函数通过第一个元素对列表进行排序

在这个方法中,我们使用 sorted() 函数,并将 lambda 函数作为 key 参数,根据每个子列表的第一个元素对列表进行排序。

# Using the sorted() Function with a Lambda Function
list_of_lists= [[3, ‘b‘], [1, ‘a‘], [2, ‘c‘]]
sorted_list= sorted(list_of_lists, key=lambda x: x[0])

#Display the sorted 
print(sorted_list)

Output

[[1, ‘a‘], [2, ‘c‘], [3, ‘b‘]]

使用 sort() 函数通过第一个元素对二维列表进行排序

在这个方法中,我们使用 sort() 方法,并将自定义比较器作为 key,根据每个子列表的第一个元素对列表进行就地排序。

#Using the sort() Method with a Custom Comparator
list_of_lists = [[3, ‘b‘], [1, ‘a‘], [2, ‘c‘]]
list_of_lists.sort(key=lambda x: x[0])

#Display the sorted list
print(list_of_lists)

Output

[[1, ‘a‘], [2, ‘c‘], [3, ‘b‘]]

Python 通过第一个元素对列表进行排序:使用列表推导式

其中一种方法是结合使用 列表推导式sorted() 函数,根据每个子列表的第一个元素创建一个新的排序列表。

# Using List Comprehension with Sorted
list_of_lists = [[3, ‘b‘], [1, ‘a‘], [2, ‘c‘]]
sorted_list = [x for x in sorted(list_of_lists, key=lambda x: x[0])]

#Display sorted list
print(sorted_list)

Output

[[1, ‘a‘], [2, ‘c‘], [3, ‘b‘]]

Python 使用 itemgetter() 函数通过第一个元素对二维列表进行排序

其中一种方法是使用 operator 模块中的 itemgetter 函数作为 sorted() 函数中的 key 参数,从而实现基于每个子列表第一个元素的排序。

#  Using the itemgetter Function from the operator Module
from operator import itemgetter
list_of_lists = [[3, ‘b‘], [1, ‘a‘], [2, ‘c‘]]
sorted_list= sorted(list_of_lists, key=itemgetter(0))

# Display sorted list
print(sorted_list)

Output

[[1, ‘a‘], [2, ‘c‘], [3, ‘b‘]]

使用自定义函数通过第一个元素对二维列表进行排序

在这个方法中,我们定义了一个自定义排序函数,并将该函数用作 sorted() 函数中的 key 参数,以根据每个子列表的第一个元素对列表进行排序。

# Using a Custom Function
def custom_sort(sub_list):
    return sub_list[0]

list_of_lists = [[3, ‘b‘], [1, ‘a‘], [2, ‘c‘]]
sorted_list = sorted(list_of_lists, key=custom_sort)
#Display list in sorted order
print(sorted_list)

Output

[[1, ‘a‘], [2, ‘c‘], [3, ‘b‘]]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/42758.html
点赞
0.00 平均评分 (0% 分数) - 0