import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
结果:
01.01.07.02 Device no. 0493971:
01.01.07.05 Holder no.
01.01.07.08 Socket WAF
01.01.07.10 Fixture
01.01.07.12 Measuring device n
01.01.07.16 Tool
01.01.07.19 Test
01.01.07.20 Measurement