【发布时间】:2015-09-15 08:25:18
【问题描述】:
代码如下:
编辑**** 请不要再“使用无序的字典回复是不可能的”。我几乎已经知道了。我发表这篇文章是因为它可能是可能的,或者有人有一个可行的想法。
#position equals some set of two dimensional coords
for name in self.regions["regions"]: # I want to start the iteration with 'last_region'
# I don't want to run these next two lines over every dictionary key each time since the likelihood is that the new
# position is still within the last region that was matched.
rect = (self.regions["regions"][name]["pos1"], self.regions["regions"][name]["pos2"])
if all(self.point_inside(rect, position)):
# record the name of this region in variable- 'last_region' so I can start with it on the next search...
# other code I want to run when I get a match
return
return # if code gets here, the points were not inside any of the named regions
希望代码中的 cmets 能很好地解释我的情况。假设我最后在区域“delta”内(即,键名是 delta,值将是定义其边界的坐标集)并且我还有 500 个区域。我第一次发现自己在区域 delta 中时,代码可能直到(假设)第 389 次迭代才发现这一点……所以它在发现之前进行了 388 次all(self.point_inside(rect, position)) 计算。由于下次运行时我可能仍处于 delta 中(但每次代码运行时我都必须验证),如果键“delta”是第一个被 for 循环检查的键,将会很有帮助。
这个特定的代码每秒可以为许多不同的用户运行多次。所以速度至关重要。设计是这样的,用户不会在一个区域中,并且所有 500 条记录可能需要循环通过并且将在没有匹配项的情况下退出循环,但我想通过加速整个程序来加速它那些目前在其中一个地区的人。
我不希望以任何特定顺序对字典进行排序等额外开销。我只希望它从成功匹配的最后一个开始查找all(self.point_inside(rect, position))
也许这会有所帮助。以下是我正在使用的字典(仅显示第一条记录),因此您可以看到我在上面编码的结构...是的,尽管名称为“rect”代码,它实际上检查立方体区域中的点。
{"regions": {"shop": {"flgs": {"breakprot": true, "placeprot": true}, "dim": 0, "placeplayers": {"4f953255-6775-4dc6- a612-fb4230588eff": "SurestTexas00"}, "breakplayers": {"4f953255-6775-4dc6-a612-fb4230588eff": "SurestTexas00"}, "protected": true, "banplayers": {}, "pos1": [ 5120025, 60, 5120208], "pos2": [5120062, 73, 5120257], "ownerUuid": "4f953255-6775-4dc6-a612-fb4230588eff", "accessplayers": {"4f953255-6774-2056-a612-b ": "SurestTexas00"}},更多,更多,更多...}
【问题讨论】:
-
字典是任意排序的。如果您想要某种缓存或优化行为,我认为您需要超越内置类型和函数。
-
我知道它们是任意订购的……这就是我提出问题的原因。我知道我可以直接通过 self.regions["regions"]["""whatever last region is"""] 直接访问可能的可能性,然后如果不匹配就检查整个字典,但它会如果它可以从可能的第一个开始,则更简单(因为它们是任意的)。我怀疑任何优化或缓存都不会那么有用,因为多个用户同时访问相同的数据......除了让这一切变得更加复杂之外。
-
你的 thing 能否有一个属性来指示它所在的最后一个区域 -
self.where_i_was_last或self.region_i_was_in_last_time_i_looked?? -
# record the name of this region in variable- 'last_region' so I can start with it on the next search...行是(对于该用户)我将记录他们所在区域的位置...由于每个人都说不可能从特定键开始,我不知道如何做类似的事情:```搜索(lastkey):找到它:Do_foo_code Dangit:For Loop All:搜索(All):Do_foo_code``` -
dangit 因为无法将其格式化为代码... :(
标签: python performance python-2.7 for-loop dictionary