0

Need to sort given tuples list with last element

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

With tuples list's like ([(1, 3), (3, 2), (2, 1)]) or ([(2, 3), (1, 2), (3, 1)]) it returns correctly: ([(2, 1), (3, 2), (1, 3)]) and ([(3, 1), (1, 2), (2, 3)]) but with 3+ element tuples or 4 tuples lists it writes "list index out of range"

Lorrain
  • 73
  • 5

2 Answers2

5
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)]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0
a=([(1, 3), (3, 2), (2, 1)])
def foo(elem):
    return elem[-1]
a.sort(key=foo)
print(a)
  • 1
    Please add an explanation of your code. Someone who can understand it without a description also can write the code themselves. – jpaugh Aug 17 '17 at 18:28