需要优化此代码,以便按其y坐标的降序对坐标进行排序

时间:2019-06-07 06:49:45

标签: python-3.x

我有这段代码按其y坐标的降序对3个坐标进行排序,但是我觉得可以用更少的代码来解决相同的问题。有人可以帮助我优化它吗?

import time

coord1 = [500, 0]
coord2 = [750, 5]
coord3 = [120, 1]

start = time.time()

if coord1[1] > coord2[1] and coord1[1] > coord3[1]:
    print('First is coord1:',coord1)
    if coord2[1] > coord3[1]:
        print('Second is coord2:',coord2)
        print('Third is coord3:',coord3)
    else:
        print('Second is coord3:',coord3)
        print('Third is coord2,:',coord2)

elif coord2[1] > coord1[1] and coord2[1] > coord3[1]:
    print('First is coord2:',coord2)
    if coord1[1] > coord3[1]:
        print('Second is coord1:',coord1)
        print('Third is coord3:',coord3)
    else:
        print('Second is coord3:',coord3)
        print('Third is coord1:',coord1)

elif coord3[1] > coord1[1] and coord3[1] > coord2[1]:
    print('First is coord3:', coord3)
    if coord1[1] > coord2[1]:
        print('Second is coord1:',coord1)
        print('Third is coord2:',coord2)
    else:
        print('Second is coord2:',coord2)
        print('Third is coord1:',coord1)

end = time.time()

total = (end - start)
print('Total time taken:',total)

它运行良好,得到的结果是:

First is coord2: [750, 5]
Second is coord3: [120, 1]
Third is coord1: [500, 0]

然而,所花费的时间为0.016秒,这看起来似乎不多,但是这将成为一个更大的程序的一部分,该程序需要快速有效地工作。 我也觉得这是执行一个相当小的功能的大量代码,因此,无论如何我都可以缩短它,请告诉我!

1 个答案:

答案 0 :(得分:0)

# -*- coding: utf-8 -*-
"""
Created on Fri Jun  7 12:22:23 2019

@author: jainil
"""

import time

coord1 = [500, 0]
coord2 = [750, 5]
coord3 = [120, 1]

start = time.time()

lista=[]
lista.append(coord1)
lista.append(coord2)
lista.append(coord3)
lista.sort(key = lambda x: x[1])


end = time.time()

print(lista)
total = (end - start)
print('Total time taken:',total)