【发布时间】:2019-05-25 14:52:39
【问题描述】:
我有一个坐标列表(x 和 y 像这样:coordinates = [[1, 2], [2, 3]] 但更大),每次迭代都会更新(附加新列表)。所以我需要搜索current_pos(也是[4, 10]之类的列表)是否在coordinates中。这是我的sn-p代码:
for move in range(len(movement_string)):
# ...
# code changes current_pos
# ...
if current_pos in coordinates:
fail = True
failed_move = move + 1
break
else:
coordinates.append(current_pos)
它适用于小型列表,但对于包含 10.000 - 1.000.000 个项目的大型列表来说需要很长时间。我认为问题在于通过列表搜索,因为随着它变得更大,它使用的时间也变得更长。
【问题讨论】:
-
如果
coordinates的顺序无关紧要,那么它可以是一组元组而不是列表列表。然后current_pos in coordinates变成O(1)操作而不是O(n) -
什么是
movement_string? -
@Austin 它只是一个类似
DDRRRULLDL的字符串,表示转向哪个方向,这会改变current_pos。 -
@DeepSpace 是的,它成功了!谢谢!