Python 搜索大列表

Python 搜索大列表,python,list,search,Python,List,Search,我有一个坐标x和y的列表,如下所示:坐标=[[1,2],[2,3]],但更大的是每次迭代都会更新新的列表。所以我需要搜索当前的位置,它也是一个类似于[4,10]的列表,是否在坐标中。以下是我的代码片段: for move in range(len(movement_string)): # ... # code changes current_pos # ... if current_pos in coordinates: fail = True

我有一个坐标x和y的列表,如下所示:坐标=[[1,2],[2,3]],但更大的是每次迭代都会更新新的列表。所以我需要搜索当前的位置,它也是一个类似于[4,10]的列表,是否在坐标中。以下是我的代码片段:

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个项目的大列表,它需要花费太长的时间。我认为问题在于搜索列表,因为它越大,使用的时间也越长。

只需将坐标设置为一组即可

并将当前位置设置为元组,以便可以将其插入到集合中。在某个时刻:

current_pos = tuple(current_pos)
然后您的循环变成:

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.add(current_pos)
就这样。您将获得O1查找,因此它不依赖于坐标集的长度


如果顺序很重要,只需如上所述创建一个集合,并保留列表,以便在尚未广泛覆盖的情况下附加到:。

如果坐标顺序不重要,则它可以是一组元组,而不是列表。然后坐标中的当前位置变为O1操作,而不是什么是移动字符串?@Austin它只是一个类似DDRRULLDL的字符串,表示转向的方向,这会改变当前位置。@DeepSpace是的,它起作用了!谢谢我也有同样的想法。值得把它变成一个答案
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.add(current_pos)