Python,for循环,在调用方法时不重置有罪证明

Python,for循环,在调用方法时不重置有罪证明,python,Python,我想了解的部分是,当我调用seekNextStation()时,如何保持有罪。此时,它会将计数器更改为1,返回索引[1]中的站点,然后将计数器更改为2,但当我再次调用它时,它会将计数器重置为0,并重复相同的步骤当您可以重新绑定for循环的索引变量时,结果将持续到下一次迭代开始。然后Python将其重新绑定到传递给for循环的序列中的下一项 看起来你正在尝试建立一种复杂的方式来循环通过车站。这种类型的东西很常见,可以包含在std库中 def seekNextStation(self):

我想了解的部分是,当我调用seekNextStation()时,如何保持有罪。此时,它会将计数器更改为1,返回索引[1]中的站点,然后将计数器更改为2,但当我再次调用它时,它会将计数器重置为0,并重复相同的步骤

当您可以重新绑定for循环的索引变量时,结果将持续到下一次迭代开始。然后Python将其重新绑定到传递给for循环的序列中的下一项

看起来你正在尝试建立一种复杂的方式来循环通过车站。这种类型的东西很常见,可以包含在std库中

  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

如果需要,可以保留一个全局
计数器
变量。我不想撒谎,我嘲笑“有罪”。你想要的词是递增。这是一个类的方法吗?如果是这样,您需要使
计数器
成为类的字段,而不是方法中的局部变量。6从何而来?是不是
len(self.stations)
?@OpenUserX03lol@JasonM.Owens这是一种方法,我需要把它放在方法的一边。
>>> 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'