繁体   English   中英

如何使列表索引更快?

[英]How to make indexing of a list faster?

我有一个未排序的x,y,z列表,希望基本上以正确的方式对它们进行排序,以便更轻松地获得所需的内容。 我使用以下代码创建索引列表。 代码按应有的方式工作,我得到了索引列表。 但是,这样做很慢,而且花费的时间太长。 有哪些方法可以使下面的函数运行更快?

def index_collision_list(obstacle_list):
    min_x = -40
    min_y = -40
    min_z = -2

    max_x = 40
    max_y = 40
    max_z = 20
    indexed_list = []
    indexed_list_append=indexed_list.append
    for ix in range((max_x - min_x) * 2):
        curr_list_x = []
        curr_list_x_append=curr_list_x.append
        for iy in range((max_y - min_y) * 2):
            curr_list_y = []
            curr_list_y_append=curr_list_y.append
            for iz in range((max_z - min_z) * 2):
                curr_list_z = []
                curr_list_y_append(curr_list_z)
            curr_list_x_append(curr_list_y)
        indexed_list_append(curr_list_x)

    for i in range(len(obstacle_list)):
        curr_x = obstacle_list[i].x
        curr_y = obstacle_list[i].y
        curr_z = obstacle_list[i].z
        rounded_x = round_of_rating(curr_x, min_x)
        rounded_y = round_of_rating(curr_y, min_y)
        rounded_z = round_of_rating(curr_z, min_z)

        indexed_list[rounded_x][rounded_y][rounded_z].append(obstacle_list[i])

    return indexed_list


def round_of_rating(number, min_val):
    round_num = round(number * 2) / 2
    round_num = int((round_num - min_val) * 2)

    return round_num

而不是构造(80 * 2)*(80 * 2)*(22 * 2)= 1,126,400个列表开始,也许只是使用以3元组索引的字典?

这应该具有更高的性能,尤其是在结果单元格稀疏的情况下(即,如果您不希望所有单元格中都包含obstacle )。

经常使用的collections.defaultdict使它非常优雅:

from collections import defaultdict

def round_of_rating(number, min_val):
    round_num = round(number * 2) / 2
    round_num = int((round_num - min_val) * 2)
    return round_num


def index_collision_list(obstacle_list):
    min_x = -40
    min_y = -40
    min_z = -2    
    by_rounded_coords = defaultdict(list)

    for obstacle in obstacle_list:
        rounded_x = round_of_rating(obstacle.x, min_x)
        rounded_y = round_of_rating(obstacle.y, min_y)
        rounded_z = round_of_rating(obstacle.z, min_z)
        by_rounded_coords[rounded_x, rounded_y, rounded_z].append(obstacle)

    return by_rounded_coords

如果这还不够快,您应该考虑使用八叉树,就像@SpoonMeiser在评论中提到的那样。

编辑:defaultdict支持实现比原来用小的障碍计数快非常多(当均匀分布到空间)和接近速度(或缺乏)的原执行的,符合市场预期,当有更多的人,但似乎从未比原始版本慢。 注意两个轴都是对数的。 Y轴是两个函数每执行5次所花费的秒数。

在此处输入图片说明

您可以使用带有关键参数https://www.geeksforgeeks.org/python-list-sort/的内置方法sort()更快地对列表进行排序

def sort_func():
    #your func

your_list.sort(key=sort_func) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM