[英]How do I sort a list of numbers based on the last two digits?
Is it possible?是否可以? I have to sort it without the sort functions but I want to see if I can sort it based on the last two digits.
我必须在没有排序功能的情况下对其进行排序,但我想看看是否可以根据最后两位数字对其进行排序。
You can use the built in list.sort
method or sorted
function with a key
function.您可以使用内置的
list.sort
方法或带有key
函数的sorted
函数。 The function lambda n: abs(n) % 100
gets the last two digits:函数
lambda n: abs(n) % 100
获取最后两位数字:
>>> nums = [99, 888, 7777, 66666, 555555]
>>> sorted(nums, key=lambda n: abs(n) % 100)
[555555, 66666, 7777, 888, 99]
The abs
makes it work for negative numbers as well. abs
也适用于负数。 If your list has no negative numbers, you can just write n % 100
.如果您的列表没有负数,您可以只写
n % 100
。
If you are sorting using your own algorithm, one way is to follow the " decorate, sort, undecorate " pattern: build a list of pairs where the first component is the sort key, then write your sorting algorithm as normal, then extract the original values to return the sorted list.如果您使用自己的算法进行排序,一种方法是遵循“装饰、排序、取消装饰”模式:构建一个对的列表,其中第一个组件是排序键,然后照常编写排序算法,然后提取原始数据返回排序列表的值。
def sort_by_last_two_digits(nums):
nums = [(abs(n) % 100, n) for n in nums]
# do the sorting normally
return [n for _, n in nums]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.