📜  Python - 按列表中的单位数字排序

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

Python - 按列表中的单位数字排序

给定一个整数列表,按单位数字排序。

方法 #1:使用 sort() + str()

在这里,我们使用sort()进行排序, str()用于将整数转换为字符串,然后按最后一位数字排序。

Python3
# Python3 code to demonstrate working of
# Sort by Units Digit in List
# Using sort() + str()
  
# helpr_fnc to sort
  
  
def unit_sort(ele):
  
    # get last element
    return str(ele)[-1]
  
  
# initializing lists
test_list = [76, 434, 23, 22342]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# inplace sort by unit digits
test_list.sort(key=unit_sort)
  
# printing result
print("The unit sorted list : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort by Units Digit in List
# Using sorted() + lambda + str()
  
# initializing lists
test_list = [76, 434, 23, 22342]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# inplace sort by unit digits
res = sorted(test_list, key=lambda sub: str(sub)[-1])
  
# printing result
print("The unit sorted list : " + str(res))


输出:

The original list is : [76, 434, 23, 22342]
The unit sorted list : [22342, 23, 434, 76]

方法 #2:使用 sorted() + lambda + str()

在这里,我们使用sorted()执行排序任务,并且使用 lambda函数来避免外部函数调用。

蟒蛇3

# Python3 code to demonstrate working of
# Sort by Units Digit in List
# Using sorted() + lambda + str()
  
# initializing lists
test_list = [76, 434, 23, 22342]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# inplace sort by unit digits
res = sorted(test_list, key=lambda sub: str(sub)[-1])
  
# printing result
print("The unit sorted list : " + str(res))

输出:

The original list is : [76, 434, 23, 22342]
The unit sorted list : [22342, 23, 434, 76]