Last active
February 2, 2020 06:49
-
-
Save e96031413/ab94fa1984ec1d7d491d2675c855c608 to your computer and use it in GitHub Desktop.
處理natural sorting排列順序問題 - 例如:原本應該是:1,2,12,15,電腦會變成:1,12,15,2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# original from https://stackoverflow.com/a/5967539 | |
# 使用sort()方法時需要注意資料型態必須為list | |
import re | |
def atoi(text): | |
return int(text) if text.isdigit() else text | |
def natural_keys(text): | |
''' | |
alist.sort(key=natural_keys) sorts in human order | |
http://nedbatchelder.com/blog/200712/human_sorting.html | |
(See Toothy's implementation in the comments) | |
''' | |
return [ atoi(c) for c in re.split(r'(\d+)', text) ] | |
alist=[ | |
"something1", | |
"something12", | |
"something17", | |
"something2", | |
"something25", | |
"something29"] | |
alist.sort(key=natural_keys) | |
print(alist) | |
#['something1', 'something2', 'something12', 'something17', 'something25', 'something29'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment