如何使用嵌套循环改进此代码?

时间:2015-10-09 21:03:15

标签: python loops

我有一个函数可以计算每帧中两点之间的碰撞次数。 我不知道如何改进这个非常慢的代码。

     #data example
     #[[89, 814, -77.1699249744415, 373.870468139648, 0.0], [71, 814, -119.887828826904, 340.433287620544, 0.0]...]

    def is_collide(data, req_dist):
        #req_dist - minimum distance when collision will be count

        temp = data 

        temp.sort(key=Measurements.sort_by_frame)
        max_frame = data[-1][1]
        min_frame = data[0][1]
        collissions = 0

        # max_frame-min_frame approximately 60000
        # the slowest part
        for i in range(min_frame, max_frame):
            frames = [line for line in temp if line[1] == i]
            temp = [line for line in temp if line[1] != i]
            l = len(frames)

            for j in range(0, l, 1):
                for k in range(j+1, l, 1):
                    dist = ((frames[j][2] - frames[k][2])**2 + (frames[j][3]-frames[k][3])**2)**0.5
                    if dist < req_dist:
                        collissions += 1

        return collissions

0 个答案:

没有答案