通过Python中元组的第一个元素自然地对字母数字元组列表进行排序 [英] Naturally sort a list of alpha-numeric tuples by the tuple's first element in Python
问题描述
一个先前的stackoverflow问题解释了如何对一个字母数字字符串列表.我想按元组的第一个元素按字母顺序对元组列表进行排序.
A previous stackoverflow question explains how to sort a list of strings alpha-numerically. I would like to sort a list of tuples alphanumerically by the tuple's first element.
示例1:
>>> sort_naturally_tuple([('b', 0), ('0', 1), ('a', 2)])
[('0', 1), ('a', 2), ('b', 0)]
示例2:
>>> sort_naturally_tuple([('b10', 0), ('0', 1), ('b9', 2)])
[('0', 1), ('b9', 2), ('b10', 0)]
更新:要强调字母数字因子,请查看示例2.
Update: To emphasize the alphanumeric factor, please review example 2.
推荐答案
使用另一个问题的第二个答案,一般来说,它支持基于项目的任何方法作为获取密钥的基础:
Using the second answer from the other question, generalized to support any method on item as the basis for getting the key:
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.itemgetter(key_or_index_you_want)
它可以在类实例上使用operator.attrgetter('attribute_name_you_want')
.
This is exactly the same as that answer except generalized to use any callable as the operation on item. If you just wanted to do it on a string, you'd use lambda item: item
, if you wanted to do it on a list, tuple, dict, or set, you'd use operator.itemgetter(key_or_index_you_want)
, or if you wanted to do it on a class instance you could use operator.attrgetter('attribute_name_you_want')
.
它给出
[('0', 1), ('b9', 2), ('b10', 0)]
对于您的示例2.
这篇关于通过Python中元组的第一个元素自然地对字母数字元组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!