Here is one way to do this:
>>> import functools
>>> def cmp(s, t):
'Alter lexicographic sort order to make longer keys go *before* any of their prefixes'
ls, lt = len(s), len(t)
if ls < lt: s += t[ls:] + 'x'
elif lt < ls: t += s[lt:] + 'x'
if s < t: return -1
if s > t: return 1
return 0
>>> sorted(l, key=functools.cmp_to_key(cmp))
['A1', 'A2', 'A3', 'A', 'B1', 'B2', 'B3', 'B']
Traditionally, the lexicographic sort order is longer than the lines after their identical identical prefixes (i.e., 'abc' goes before 'abcd').
, "" , , :
compare abc to defg --> compare abcgx to defg
compare a to a2 --> compare a2x to a2
functools.cmp_to_key() .
, .
FWIW, , :
def cmp(s, t):
'Alter lexicographic sort order to make longer keys go *before* any of their prefixes'
for p, q in zip(s, t):
if p < q: return -1
if q < p: return 1
if len(s) > len(t): return -1
elif len(t) > len(s): return 1
return 0
: