2017-04-25 73 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'