首页 > 解决方案 > Python:遍历两个列表,如果满足条件,则添加到它们,但每次都遍历列表的每个元素

问题描述

如果我运行一次,它将工作并返回成功。然后,当循环再次运行时,它只会检查列表的最后一个元素。如何执行此操作以使循环运行并检查条件语句中列表的每个元素?

def draw():
    mesasX, mesasY = [], []
    x, y = random.randint(6,94), random.randint(6,94)
    mesasX.append(x)
    mesasY.append(y)
    for mesax, mesay in zip(mesasX, mesasY):
        x, y = random.randint(6,94), random.randint(6,94)
        if (x - 8 < mesax < x + 8 and y + 8 > mesay > y - 8):
            print("Failed")
        else:
            mesasX.append(x)
            mesasY.append(y)
            print("Success!")  
            break

标签: python

解决方案


您想将每个新项目与每个旧项目进行比较。这样做的方法是移动循环。并使用all

def draw():
    mesasX, mesasY = [], []
    x, y = random.randint(6,94), random.randint(6,94)
    mesasX.append(x)
    mesasY.append(y)
    while True:
        x, y = random.randint(6,94), random.randint(6,94)
        if all(x - 8 < mesax < x + 8 and y + 8 > mesay > y - 8 
               for mesax, mesay in zip(mesasX, mesasY)):
            print("Failed")
        else:
            mesasX.append(x)
            mesasY.append(y)
            print("Success!")  
            break

这读起来像这样生成一个项目测试,如果它适合,如果它不重试,如果它确实将它添加到列表并停止。

如果将列表替换为以某个点为中心的 16 x 16 单位框的空间索引,则可以更快地完成此操作。这将允许一个人将近距离测试转变为可以接近恒定时间的盒子测试中的点。

然后,如果一个人可以从这些盒子的联合中统一采样,那将删除测试,因为每个生成的项目都会通过测试。


推荐阅读