Python - 按位数对列表项进行排序
当需要根据数字对列表的元素进行排序时,可以使用“max”、”max”方法。我们还将使用“sorted”方法、”lambda”函数和“ljust”。
示例
以下是对相同内容的演示 -
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]
说明
定义了一个字符串列表,并显示在控制台上。
使用排序方法对列表进行排序,并显示在控制台上。
使用“map”方法将列表中的所有元素转换为字符串。
这会分配给一个变量
找到列表中最大元素并分配给一个变量。
使用排序方法对列表进行排序,键是具有左对齐功能的 lambda 函数。
这会分配给结果。
这作为输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP