📌  相关文章
📜  Python – 根据数字对列表项进行排序

📅  最后修改于: 2022-05-13 01:54:32.410000             🧑  作者: Mango

Python – 根据数字对列表项进行排序

给定元素列表,根据数字进行排序。

方法 #1:使用 map() + str() + ljust() + sorted()

这里使用map() 和str() 将列表元素转换为字符串,ljust() 用于附加常量字符以使每个数字等长。然后使用 sorted() 执行排序。

Python3
# Python3 code to demonstrate working of 
# Sort List by Digits
# Using map() + str() + ljust() + sorted()
  
# initializing list
test_list = [434, 211, 12, 54, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# converting elements to string 
temp1 = map(str, test_list)
  
# getting max length
max_len = max(map(len, temp1))
  
# performing sort operation
res = sorted(test_list, key = lambda idx : (str(idx).ljust(max_len, 'a')))
  
# printing result 
print("List after sorting : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sort List by Digits
# Using list comprehension + sorted() + lambda
  
# initializing list
test_list = [434, 211, 12, 54, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort operation
# converting number to list of Digits
res = sorted(test_list, key = lambda ele: [int(j) for j in str(ele)])
  
# printing result 
print("List after sorting : " + str(res))


输出
The original list is : [434, 211, 12, 54, 3]
List after sorting : [12, 211, 3, 434, 54]

方法 #2:使用列表理解 + sorted() + lambda

在此,我们作为 sorted() 的参数,传递一个数字列表。根据它执行排序会产生所需的结果。

Python3

# Python3 code to demonstrate working of 
# Sort List by Digits
# Using list comprehension + sorted() + lambda
  
# initializing list
test_list = [434, 211, 12, 54, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort operation
# converting number to list of Digits
res = sorted(test_list, key = lambda ele: [int(j) for j in str(ele)])
  
# printing result 
print("List after sorting : " + str(res))
输出
The original list is : [434, 211, 12, 54, 3]
List after sorting : [12, 211, 3, 434, 54]