使用最后一个元素对元组列表进行排序

时间:2017-08-16 12:20:06

标签: python python-2.7

需要使用最后一个元素

对给定的元组列表进行排序
def sort_last(tuples):
    sorted_list = []
    i = 0
    i2 = 1
    while True:
        if len(tuples) == 2:
            if tuples[i][-1] < tuples[i2][-1]:
                sorted_list.append(tuples[i])
                sorted_list.append(tuples[i2])
                break
            else:
                sorted_list.append(tuples[i2])
                sorted_list.append(tuples[i])
                break
        elif tuples[i][-1] < tuples[i2][-1]:
            i2 += 1
            print 1
        elif i == i2:
            i2 += 1
        elif i2 == len(tuples)-1:
            if tuples[i][-1] < tuples[i2][-1]:
                sorted_list.append(tuples[i])
                del tuples[i]
                i = 0
                i2 = 1
            else:
                sorted_list.append(tuples[i2])
                del tuples[i2]
                i = 0
                i2 = 1
        elif len(tuples) <= 1:
            return tuples
        else:
            i += 1
    return sorted_list

使用([(1, 3), (3, 2), (2, 1)])([(2, 3), (1, 2), (3, 1)])之类的元组列表,它会正确返回:([(2, 1), (3, 2), (1, 3)])([(3, 1), (1, 2), (2, 3)])但是有3个元素元组或4个元组列表,它会写{{1} }

2 个答案:

答案 0 :(得分:4)

def sort_last(tuples):
    return sorted(tuples, key=lambda i: i[-1])

>>> sort_last([(1, 3), (3, 2), (2, 1)])
[(2, 1), (3, 2), (1, 3)]
>>> sort_last([(2, 3), (1, 2), (3, 1)])
[(3, 1), (1, 2), (2, 3)]

答案 1 :(得分:0)

a=([(1, 3), (3, 2), (2, 1)])
def foo(elem):
    return elem[-1]
a.sort(key=foo)
print(a)