我需要一些帮助来开始这个广播节目

2024-09-28 21:13:20 发布

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

我需要的帮助是,如果用户按3,就让电台切换到列表中的下一个电台。你知道吗

class Radio:
def __init__(self):
    self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
    self.stationStart=self.stations[0]
def seekNext(self):
    self.stationsStart

它从静态开始,但我希望它改变每一个,然后重新开始。我试过这样的方法:

stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
a =input("enter 3 to seek next")
while a !="0":
   if a =="3":
      print(stations[-1])

我只得到最后一个电台,却不知道如何列出其余电台。你知道吗


Tags: 方法用户self列表initdef静态static
3条回答

用实际位置在init中定义一个变量“自身位置=0”,并在需要时调用此函数

def seekNext(self):
    if(self.pos == (len(self.stations)-1)):
        self.pos = 0
    else:
        self.pos += 1
    print(self.stations[self.pos])
index = 0

if a=="3":
    index = (index+1)%6
    print(stations[index])

有几个合理的方法来做你想做的事。你知道吗

最简单的方法是让类将索引存储到列表中,而不是直接存储列表项。这样,您就可以增加索引并使用%模运算符将其环绕:

class Radio:
    def __init__(self):
        self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
        self.station_index = 0

    def seek(self):
        print("Currently tuned to", self.stations[self.station_index])
        print("Seeking...")
        self.station_index = (self.station_index + 1) % len(self.stations)
        print("Now tuned to", self.stations[self.station_index])

解决这个问题的一种“更奇特”的、可能更具Python风格的方法是使用Python标准库中的itertools模块中的cycle生成器。它返回一个迭代器,该迭代器从您的列表中生成值,在到达末尾时重新开始。虽然您通常只处理for循环中的迭代器,但是手工使用iterator protocol也很容易。在本例中,我们只想调用迭代器上的next,以获得下一个值:

import itertools

class Radio:
    def __init__(self):
        self.stations = itertools.cycle(["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"])
        self.current_station = next(self.stations)

    def seek(self):
        print("Currently tuned to", self.current_station)
        print("Seeking...")
        self.current_station = next(self.stations)
        print("Now tuned to", self.current_station)

相关问题 更多 >