python - 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
解决方案
您想将每个新项目与每个旧项目进行比较。这样做的方法是移动循环。并使用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 单位框的空间索引,则可以更快地完成此操作。这将允许一个人将近距离测试转变为可以接近恒定时间的盒子测试中的点。
然后,如果一个人可以从这些盒子的联合中统一采样,那将删除测试,因为每个生成的项目都会通过测试。
推荐阅读
- qt - 在 Qt 中使用按钮堆叠小部件页面
- amazon-web-services - AppSync Java 使用 IAM 进行身份验证
- security - 如何使用 npm request-promise 在 api 请求中发送 crt 文件
- node.js - Heroku Node.js RedisCloud Redis::CannotConnectError 在 localhost 而不是 REDISCLOUD_URL
- r - 在 R + 中的地图上映射采样点,在同一地图中创建区域的放大
- postgresql - PostgreSql 用户没有发现任何关系
- asp.net - HttpRequestMessage.GetClientCertificate() 在 ASP Web API DelegatingHandler 中返回 null
- javascript - react-d3-graph 设置节点的起始位置
- libreoffice - Libreoffice:斜体中断(替换功能混乱)
- ios - 快速获取并检查内部(本地)JSON文件