Python While循环 - 变量不更新?

时间:2015-11-07 22:12:15

标签: python variables while-loop python-3.5

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

我不明白为什么我的变量next_y没有更新,因为posnext_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))

2 个答案:

答案 0 :(得分:0)

如评论中所述,如果您要更新next_y,则需要明确

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

答案 1 :(得分:0)

您不会在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))
相关问题