在python3中发出排序元组

时间:2017-09-03 00:10:23

标签: python sorting python-3.4

下面是我的代码,我试图根据第二个元素对元组进行排序。

list = ["abc14_90","abc44_88","abc14_89"]
listLength = len(list)
for i in range(0,listLength):
    tempList = list[i].split('_')
    tempList1 = tempList[0].split('c')
    if(i==0):
        tupleNumber = [(list[i], int(tempList1[1]),int(tempList[1]))]
    else:
        tupleNumber = tupleNumber + [(list[i], int(tempList1[1]),int(tempList[1]))]

print (tupleNumber)

sorted(tupleNumber, key=lambda x: x[2])

print (tupleNumber)

预期产出:

[ ('abc44_88', 44, 88), ('abc14_89', 14, 89),('abc14_90', 14, 90),]

观察到的输出:

[('abc14_90', 14, 90), ('abc44_88', 44, 88), ('abc14_89', 14, 89)]

基本上这种排序似乎没有效果。

2 个答案:

答案 0 :(得分:0)

sorted()没有排序,但会返回排序列表,因此您需要将列表重新分配给tupleNumber,如下所示:

print (tupleNumber)

tupleNumber = sorted(tupleNumber, key=lambda x: x[2])

print (tupleNumber)

答案 1 :(得分:0)

你可以试试这个:

import re
import itertools
l = ["abc14_90","abc44_88","abc14_89"]
new_l = [tuple(itertools.chain.from_iterable([[i], map(int, re.findall("\d+", i))])) for i in sorted(l, key=lambda x: int(x[-2:]))]

输出:

[('abc44_88', 44, 88), ('abc14_89', 14, 89), ('abc14_90', 14, 90)]