Python - 按位数对列表项进行排序


当需要根据数字对列表的元素进行排序时,可以使用“max”、”max”方法。我们还将使用“sorted”方法、”lambda”函数和“ljust”。

示例

以下是对相同内容的演示 -

Open Compiler
my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) my_temp_val = map(str, my_list) my_max_length = max(map(len, my_temp_val)) my_result = sorted(my_list, key = lambda index : (str(index).ljust(my_max_length, 'a'))) print("The resultant list is : ") print(my_result)

输出

The list is :
[4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]
The list after sorting is :
[1, 10, 33, 120, 122, 390, 460, 541, 892, 2611, 2909, 4344, 11239, 48292]
The resultant list is :
[10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个字符串列表,并显示在控制台上。

  • 使用排序方法对列表进行排序,并显示在控制台上。

  • 使用“map”方法将列表中的所有元素转换为字符串。

  • 这会分配给一个变量

  • 找到列表中最大元素并分配给一个变量。

  • 使用排序方法对列表进行排序,键是具有左对齐功能的 lambda 函数。

  • 这会分配给结果。

  • 这作为输出显示在控制台上。

更新于: 13-9-2021

289 浏览

开启您的职业生涯

通过完成课程获得认证

开始
广告