把字符串按照字符数字拆分成list,方便排序
下面的函数会把字符串拆分成list
def splitStrByWord(s):
tmpList = list()
try:
a = re.search(r"(\D+)", s).group()
nextIsWord = True
if not s.startswith(a):
nextIsWord = False
while s:
if nextIsWord:
a = re.search(r"(\D+)", s).group()
tmpList.append(a)
else:
a = re.search(r"(\d+)", s).group()
tmpList.append(int(a))
s = s[len(a):]
nextIsWord = not nextIsWord
except Exception:
pass
return tmpList
下面的函数是一个字符串list的排序回调函数,keyList.sort(cmp=sortFunc),执行后keyList 里就按字母和数字排好顺序了。
比如原始是:
G5R1
G4C8
G5R10
G4C10
G5R4
G5C12
G4C11
G4C2
G5U1
G5C3
G5C7
G5C14
G4C1
G4C9
G5R11
G5F1
G5L1
排序后是:
G4C1
G4C2
G4C8
G4C9
G4C10
G4C11
G5C3
G5C7
G5C12
G5C14
G5F1
G5L1
G5R1
G5R4
G5R10
G5R11
G5U1
def sortFunc(x, y):
listA = splitStrByWord(x)
listB = splitStrByWord(y)
try:
for i, s in enumerate(listA):
if s > listB[i]:
return 1
elif s < listB[i]:
return -1
except Exception:
return 1
return 0