自然地通过元组中Python的第一个元素对字母数字元组进行排序

par*_*axi 4 python sorting tuples alphanumeric natural-sort

一个以前的计算器的问题介绍了如何以字母数字排序的字符串列表.我想用元组的第一个元素按字母数字排序元组列表.

例1:

>>> sort_naturally_tuple([('b', 0), ('0', 1), ('a', 2)])
[('0', 1), ('a', 2), ('b', 0)]
Run Code Online (Sandbox Code Playgroud)

例2:

>>> sort_naturally_tuple([('b10', 0), ('0', 1), ('b9', 2)])
[('0', 1), ('b9', 2), ('b10', 0)]
Run Code Online (Sandbox Code Playgroud)

更新: 要强调字母数字因素,请查看示例2.

agf*_*agf 5

使用另一个问题的第二个答案,概括为支持项目上的任何方法作为获取密钥的基础:

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))
Run Code Online (Sandbox Code Playgroud)

这与该答案完全相同,除了通用以使用任何可调用项作为对项的操作.如果你只想在一个字符串上做,你可以使用lambda item: item,如果你想在列表,元组,字典或集合上进行,你可以使用operator.itemgetter(key_or_index_you_want),或者如果你想在类实例上做可以使用operator.attrgetter('attribute_name_you_want').

它给

[('0', 1), ('b9', 2), ('b10', 0)]
Run Code Online (Sandbox Code Playgroud)

为你的例子#2.