Python - 按列表中的单位数字排序
给定一个整数列表,按单位数字排序。
Input : test_list = [76, 434, 23, 22342]
Output : [22342, 23, 434, 76]
Explanation : 2 < 3 < 4 < 6, sorted by unit digits.
Input : test_list = [76, 4349, 23, 22342]
Output : [22342, 23, 76, 4349]
Explanation : 2 < 3 < 6 < 9, sorted by unit digits.
方法 #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]