Python While 循环 - 变量未更新?

Python While Loop - Variable Not Updating?

此代码只是在另一个字符串中查找一个字符串,returns 在搜索字符串中出现的最后位置,如果未找到则为 -1。

考虑到 posnext_y 计算的输入,我不明白为什么我的变量 next_y 没有更新。我的想法是,如果我更新 pos,那么 next_y 也应该更新。相反 pos 得到更新并永远保持在循环中。

def find_last(x,y):
    if x.find(y) == -1:
        return -1

    pos = x.find(y)
    next_y = x.find(y, pos + 1)

    while next_y != -1:
        pos = pos + next_y

    return pos


search = 'tom ran up but tom fell down'
target = 'tom'

print(find_last(search,target))

如评论中所述,如果要更新next_y,则需要显式:

while next_y != -1:
    pos = pos + next_y
    next_y = x.find(y, pos + 1)

您没有在 while 循环中更改 next_y 的值,因此它的值不会更新。 next_y 的值计算一次并永远比较(或仅一次)。要更新此值,您应该在循环中调用 'next_y = x.find(y, pos + 1)'。

def find_last(x,y):
  if x.find(y) == -1:
    return -1
  pos = x.find(y)
  next_y = x.find(y, pos + 1)
  while next_y != -1:
    pos = pos + next_y
    next_y = x.find(y, pos + 1)
  return pos

search = 'tom ran up but tom fell down'
target = 'tom'

print(find_last(search,target))