使用另一个问题的第二个答案,泛化为支持项目上的任何方法作为获取密钥的基础:
import re
from operator import itemgetter
def sorted_nicely(l, key):
""" Sort the given iterable in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda item: [ convert(c) for c in re.split('([0-9]+)', key(item)) ]
return sorted(l, key = alphanum_key)
print sorted_nicely([('b10', 0), ('0', 1), ('b9', 2)], itemgetter(0))
这与那个答案完全相同,只是广义上使用任何可调用作为对项目的操作。如果你只是想在一个字符串上做,你会使用lambda item: item
,如果你想在列表、元组、字典或集合上做,你会使用operator.itemgetter(key_or_index_you_want)
,或者如果你想在类实例上做可以使用operator.attrgetter('attribute_name_you_want')
.
它给
[('0', 1), ('b9', 2), ('b10', 0)]
对于您的示例#2。