【问题标题】:how to loop through a list where the items of the list are constantly appended in the loop?如何循环遍历列表中的项目不断附加在循环中的列表?
【发布时间】:2020-07-26 12:45:39
【问题描述】:

我是 Python 新手。我想写一个搜索算法,可以实现如下:给定一个点→搜索一个附近满足某个条件的点→用那个新点搜索下一个附近的新点→重复这个直到找不到附近的新点.这是我的脚本,new_point_near_this_point() 是一个自定义函数,它返回布尔值是否存在满足条件的附近点。 init_point 是起点。

lst = [init_point]
for i in lst[-1]:
    if new_point_near_this_point(i):
        lst.append(new_point)
    else:
        break

但是,这不起作用,因为它只会循环通过一个初始点。我想知道如何实现一个搜索算法,该算法可以遍历一个列表,其中列表的项目在循环中不断附加(每次迭代一次)?

【问题讨论】:

  • for 循环不应该在迭代时修改列表,这非常令人困惑并且可能导致意外行为。需要更多关于 init_pointnew_point 的确切含义的信息,以便建议替代方法
  • 如果new_point_near_this_point 只返回一个布尔值,那么你怎么知道下一个点是什么?
  • 抱歉原来的混乱代码。我已将lst.append(i) 更改为lst.append(new_point)

标签: python list algorithm for-loop search


【解决方案1】:

您应该更改new_point_near_this_point,以便它不仅返回布尔值,而且返回找到的附近点。否则你无法进入下一个点。

因此,假设有一个点时new_point_near_this_point(或None 否则)返回,您可以这样做:

list = []
point = init_point
while point:
    list.append(point)
    point = new_point_near_this_point(point)

【讨论】:

    【解决方案2】:

    使用与@trincot 相同的假设,new_point_near_this_point 返回一个真正的新点,如果没有,则返回一个假值:

    lst = [init_point]
    for point in lst:
        if new_point := new_point_near_this_point(point):
            lst.append(new_point)
    

    例如,用

    init_point = 0
    def new_point_near_this_point(point):
        if point < 5:
            return point + 1
    

    你会得到列表[0, 1, 2, 3, 4, 5]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 2012-04-01
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多