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

2024-03-29 09:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

  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()时,如何保持有罪。此时,它会将counter更改为1,返回索引[1]中的电台,然后将counter更改为2,但当我再次调用它时,它会将counter重置为0,并重新执行相同的步骤


Tags: inselfforlenreturnifdefcounter
1条回答
网友
1楼 · 发布于 2024-03-29 09:12:44

虽然可以重新绑定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'

相关问题 更多 >