You can pass a custom key function to list.sort
:
x = [4,6,9,'ashley','drooks','chay','poo','may']
x.sort(key=lambda v: (isinstance(v, str), v))
# result:
# [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']
This key function maps each element in the list to a tuple in which the first value is a boolean (True
for strings and False
for numbers) and the second value is the element itself, like this:
>>> [(isinstance(v, str), v) for v in x]
[(False, 4), (False, 6), (False, 9), (True, 'ashley'), (True, 'chay'),
(True, 'drooks'), (True, 'may'), (True, 'poo')]
These tuples are then used to sort the list. Because False < True
, this makes it so that integers are sorted before strings. Elements with the same boolean value are then sorted by the 2nd value in the tuple.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…