【问题标题】:Search through big list of lists [duplicate]搜索列表的大列表[重复]
【发布时间】: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 是的,它成功了!谢谢!

标签: python list search


【解决方案1】:

只需将coordinates 转为set

coordinates = set()

然后将current_pos 设为tuple,这样您就可以将其插入set。在某些时候:

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)

就是这样。您会得到 O(1) 查找,因此它不依赖于 coordinates 集合的长度。

如果订单很重要,只需像上面一样创建一个 set 并保留 list 以附加到如果还没有看到(广泛覆盖,如这里:How do you remove duplicates from a list whilst preserving order?)。

【讨论】:

  • 我的想法完全一样。值得把它变成一个答案
猜你喜欢
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2020-06-26
  • 2013-10-28
  • 2014-09-17
  • 2014-04-21
相关资源
最近更新 更多