简体   繁体   中英

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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