如何进一步优化这段代码?

时间:2019-04-21 07:14:50

标签: python optimization

这里是否可以使用任何循环优化技术来以任何方式减少执行时间?

def get_destructors_in_radius(self, game_state, location, player_index=1):
    radius_locations = self.radius_locations_3(location)
    destructors = []
    for location2 in radius_locations:
        if location2 in self.all_locations:        
            unit = game_state.contains_stationary_unit(location2)
            if unit:
                if unit.unit_type == DESTRUCTOR and not unit.player_index == player_index:
                    destructors.append(unit)

    return destructors

1 个答案:

答案 0 :(得分:0)

如果self.all_locations是一个很长的列表,请将其转换为一个集合以快速查找。

def get_destructors_in_radius(self, game_state, location, player_index=1):
    radius_locations = self.radius_locations_3(location)
    all_locations = set(self.all_locations)
    destructors = []
    for location2 in radius_locations:
        if location2 in all_locations:        
            unit = game_state.contains_stationary_unit(location2)
            if unit:
                if unit.unit_type == DESTRUCTOR and not unit.player_index == player_index:
                    destructors.append(unit)

    return destructors

也许您可以在类本身中设置self.all_locations的集合,而不是每次调用此函数时都将其转换。

除此之外,此代码没有太多可以改进的地方。您可能必须优化其调用的功能。