在类中使用next()函数

2024-04-26 02:45:08 发布

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

我有一门课,用矩阵的概率来预测天气。矩阵很小:

weather = [
    [0.4,  0.3,  0.1,  0.05, 0.1,  0.05],
    [0.3,  0.4,  0.1,  0.1,  0.08, 0.02],
    [0.2,  0.3,  0.35, 0.05, 0.05, 0.05],
    [0.1,  0.2,  0.25, 0.3,  0.1,  0.05],
    [0.15, 0.2,  0.1,  0.15, 0.3 , 0.1 ],
    [0.1 , 0.2,  0.35, 0.1 , 0.05, 0.2 ]
]

每一行对应一种天气(按上面给出的顺序),每一列是第二天发生一种天气的概率(也按上面给出的顺序)。我写了一个计算概率的类,例如,假设前一天天气晴朗,天气会下冰雹。我将其制作成一个迭代器,如下所示:

class Markov:
    def __init__(self):
        #Initialize Markov object
        self.weather = {'sunny':0, 'cloudy':1, 'rainy':2, 
                        'snowy':3, 'windy':4, 'hailing':5}
        self.dat = np.array([])
        self.previous_day = None
        self.following_day = None

    #load data
    def load_data(self, array):
        # implement here
        self.dat = array

    # Get probability of weather on following day given weather on #previous day
    def get_prob(self, previous_day, following_day):

        self.previous_day = previous_day
        self.following_day = following_day
        return self.dat[self.weather[previous_day]][self.weather[following_day]]

    def __iter__(self):
        return self

    #function I would like to write. 
    def get_weather_for_day(self, day):
        pass

    #Implement the next function which does most of the heavy lifting. 
    def __next__(self):
        outcome = ''.join(np.random.choice(a = list(self.weather.keys()), size = 1, p=self.dat[self.weather[self.following_day]]))
        self.following_day = self.previous_day
        return "The next day's weather is " + outcome

#Run the code
weather_today = Markov()
weather_today.load_data(weather)
print(weather_today.get_prob('sunny', 'hailing'))
next(weather_today)

#Output
"The next day's weather is rainy"

>next(weather_today)
"The next day's weather is windy"
>next(weather_today)
>"The next day's weather is sunny"

这对用户来说是好的,但是很费劲。如果我想在第十天把天气还给你呢?有什么办法可以实现吗?我想要的方法是为天(self,day)获取天气,其中day指定天数。你知道吗

我的假设是我将在get_weather_for_day(self, day)中使用__next__函数,但我不确定如何实现这个功能?你知道吗

简而言之,我想要的是以下输出:

weather_today = Markov()
weather_today.load_data(weather)
weather_today.get_weather_for_day(5)

#output
In 5 days, the weather will be snowy

Tags: theselfdatagettodaydefloaddat
1条回答
网友
1楼 · 发布于 2024-04-26 02:45:08

当您的实例用作迭代器时(它将在for循环中,因为您只在__iter__中返回self)。方法__next__为每个for迭代调用。你知道吗

因此,您可以直接在for循环中使用实例,并通过索引控制迭代次数,索引可以由enumerate提供。除此之外,您可能希望在迭代之前将某些状态归零—如果是这样,请在返回self之前在__iter__内执行此操作:

class Markov:
    ...
    get_weather_for_day(self, day):
         for daycount, prediction in enumerate(self):
             if daycount == day:
                  return prediction

如果您希望(1)在调用此方法之前保留“前一天”状态,或者(2)在多线程或异步程序(例如在视图中使用此代码的web应用程序的后端)中使用此代码,则只需小心。你知道吗

在这些情况下,您可以在继续迭代之前,在函数中创建实例当前状态的副本

 from copy import copy

 class Markov:
    ...

    def __next__(self):
        outcome = ''.join(np.random.choice(a = list(self.weather.keys()), size = 1, p=self.dat[self.weather[self.following_day]]))
        self.following_day = self.previous_day
        return  outcome

    def __iter__(self):
         return copy(self)
    ...
    get_weather_for_day(self, day):

         for daycount, prediction in enumerate(iter(self)):
             if daycount == day:
                  return f"In {day} days the weather will be {prediction}!"

(啊,当然你必须自己改变__next__的返回值,这样你就可以按照你在这个函数中的要求格式化输出-)

相关问题 更多 >

    热门问题