Python中列表元组排序4种方法

在 Python 中对列表元组进行排序涉及根据特定标准排列元组内的列表。在本文中,我们将学习如何在 Python 中对列表的元组进行排序。

例子:

输入: ([2, 1, 5], [1, 5, 7], [5, 6, 5])
根据每个列表的第一个元素排序后,预期输出应为:
输出: ([1, 2, 5], [1, 5, 7], [5, 5, 6])

1、使用列表理解对列表元组进行排序
在这种方法中,使用列表理解来创建一个新的元组,其中每个内层列表都使用 sorted() 函数进行排序。

# Define a tuple of lists
tuple_of_lists = ([2, 1, 5], [1, 5, 7], [5, 6, 5])

# Sort each inner list and create a new tuple
sorted_tuple = tuple(sorted(sublist) for sublist in tuple_of_lists)

print(sorted_tuple)

2、Python使用 Map 和 Sorted 函数对列表元组进行排序
在这种方法中,我们使用map将sorted函数应用于每个内部列表,从而产生一个新的排序列表元组。

# Define a tuple of lists
tuple_of_lists = ([2, 1, 5], [1, 5, 7], [5, 6, 5])

# Use map to apply the sorted function to each inner list and create a new tuple
sorted_tuple = tuple(map(sorted, tuple_of_lists))

print(sorted_tuple)

3、
使用 Lambda 函数对列表元组进行排序
在这种方法中,列表理解用于创建新元组。lambda函数用于在排序函数中对每个内部列表进行排序,而映射函数用于将排序值转换为整数。
# Define a tuple of lists
tuple_of_lists = ([2, 1, 5], [1, 5, 7], [5, 6, 5])

# Sort each inner list using a lambda function and create a new tuple
sorted_tuple = tuple([*map(int, sorted(sublist))]
                    for sublist in tuple_of_lists)

print(sorted_tuple)


4、使用自定义函数对列表元组进行排序
在这种方法中,定义了一个自定义函数(sort_inner_list)来封装对每个内部列表进行排序的逻辑。此自定义函数采用内部列表作为参数并返回该列表的排序版本。

# Define a tuple of lists
tuple_of_lists = ([2, 1, 5], [1, 5, 7], [5, 6, 5])

# Define a custom function to sort each inner list
def sort_inner_list(inner_list):
    return sorted(inner_list)

# Sort each inner list using the custom function and create a new tuple
sorted_tuple = tuple(map(sort_inner_list, tuple_of_lists))

print(sorted_tuple)