問題描述
如何循環遍歷列表中的項目不斷附加在循環中的列表? (how to loop through a list where the items of the list are constantly appended in the loop?)
我是 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
但是,這不起作用,因為它只會循環通過一個初始點。我想知道如何實現一個可以循環遍歷列表的搜索算法,其中列表的項目在循環中不斷附加(每次迭代一次)?
參考解法
方法 1:
You should change new_point_near_this_point
so that it does not just return a boolean, but the nearby point that was found. Otherwise you have no way to progress to the next point.
So assuming that a point is returned by new_point_near_this_point
when there is one (or None
otherwise), you could do it like this:
list = []
point = init_point
while point:
list.append(point)
point = new_point_near_this_point(point)
方法 2:
With the same assumption as @trincot, that new_point_near_this_point
returns a true new point or a false value if there isn't one:
lst = [init_point]
for point in lst:
if new_point := new_point_near_this_point(point):
lst.append(new_point)
For example, with
init_point = 0
def new_point_near_this_point(point):
if point < 5:
return point + 1
you get the list [0, 1, 2, 3, 4, 5]
.
(by Shaun Han、trincot、Kelly Bundy)