2017-04-25 14 views
-1
def seekNextStation(self): 
    counter = 0 
    print(counter) 
    for counter in range(len(self.stations)): 
     counter +=1 
     print(counter) 
     if counter != 6: 
      self.currentlyTuned = self.stations[counter] 
      counter +=1 
      print(counter, "in if") 
     else: 
      counter = 1 

     return "Currently Tuned: " + self.currentlyTuned 

我試圖得到的部分是我如何在我調用seekNextStation()時保留該罪名。此刻它會將計數器更改爲1,然後將計數器更改爲2,但是當我再次調用它時,它會將計數器重置爲0並重做相同的步驟Python,for循環,調用方法時不重置該罪行

+0

如果需要,您可以保留一個全局的'counter'變量。不會說謊,我笑到「罪證」。你想要的詞是遞增的。 – OpenUserX03

+2

這是一個班的方法嗎?如果是這樣,你需要在該方法中將'counter'作爲類的一個字段而不是一個局部變量。 –

+0

6從哪裏來?它是'len(self.stations)'? –

回答

0

儘管您可以重新綁定索引for循環的變量,結果持續到下一次迭代開始。然後Python將它重新綁定到您傳遞給for循環的序列中的下一個項目

看起來您正試圖構建一種循環遍歷站點的複雜方式。這種類型的東西已經足以包含在std庫中了

>>> stations = ['station1', 'station2', 'station3', 'station4', 'station5', 'station6'] 
>>> from itertools import cycle 
>>> station_gen = cycle(stations) 
>>> next(station_gen) 
'station1' 
>>> next(station_gen) 
'station2' 
>>> next(station_gen) 
'station3' 
>>> next(station_gen) 
'station4' 
>>> next(station_gen) 
'station5' 
>>> next(station_gen) 
'station6' 
>>> next(station_gen) 
'station1' 
>>> next(station_gen) 
'station2' 
>>> next(station_gen) 
'station3' 
>>> next(station_gen) 
'station4'