2015-11-07 205 views
0

此代碼只是在另一個字符串中查找字符串,並返回搜索字符串中最後一個出現位置,如果未找到,則返回-1。Python while循環 - 變量不更新?

我不明白爲什麼我的變量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)) 
+0

不,這個假設是不正確的:「我的想法是,如果我更新'pos',那麼'next_y'也應該更新。您需要明確指定爲'next_y',即'next_y = <在此處插入內容>' –

+1

x.find()返回一個數字,它是運行時的計算結果。如果你想再次計算這個值,你需要再次調用它。 – lolopop

回答

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)) 
0

正如評論所說,如果你想更新next_y,你需要做的是明確

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