Python排序字​​符串列表

时间:2011-06-01 09:16:51

标签: python sorting

我该如何排序?

>>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"]
>>> sorted(list)
['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']>

我需要的是:

['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', 'a_23']>

所以根据“数字”排序 谢谢我提前!

2 个答案:

答案 0 :(得分:10)

你是说这个:sorted(list, key=lambda d: int(d[2:]))

答案 1 :(得分:6)

您需要编写一个“键功能”,将您的字符串转换为具有所需顺序的搜索键。例如:

def key(k):
    s, sep, i = k.partition('_')
    return (s, int(i))

>>> L = ["a_0","a_1","b_2","c_2","a_10","a_11","a_23","b_5","a_6","c_5"]
>>> sorted(L, key=key)
['a_0', 'a_1', 'a_6', 'a_10', 'a_11', 'a_23', 'b_2', 'b_5', 'c_2', 'c_5']