简体   繁体   English

按最后 2 位数字对数字列表进行排序

[英]Sort a list of number by last 2 digits

如何排序 list2=[311, 409, 313, 202, 303, 410, 401, 105, 407, 408] 到 [101 301 401 202 407 408 409 410 ] 311 313

You can get the last two digits using the remainder operator, then use the digits as key of sorted :您可以使用余数运算符获取最后两位数字,然后使用这些数字作为sorted 的键:

a = [311, 409, 305, 104, 301, 204, 101, 306, 313, 202, 303, 410, 401, 105, 407, 408]
result = sorted(a, key=lambda x: (x % 100, x))
print(result)

Output输出

[101, 301, 401, 202, 303, 104, 204, 105, 305, 306, 407, 408, 409, 410, 311, 313]

As you want to ties to be solved using the actual value the key is a tuple of the last two digits and the actual value.由于您想使用实际值来解决关系,因此键是最后两位数字和实际值的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM