【问题标题】:python function and variablepython函数和变量
【发布时间】:2013-04-05 14:20:54
【问题描述】:

由于不够清晰,我重新编辑了我的问题。下面的代码获取一个随机数,然后检查它是否是一个新高,如果是一个则记录它。然后经过一定的延迟(1 分钟)后,它会再次执行相同的操作,从上一周期的最后一个数字开始。

我想在不同的频率上运行相同的,所以我会有很多时间段,我是否应该在函数中重写下面的代码,例如,我可以获得 agregateinfrequency(5min),它只会返回下面的打印(或列表)

希望现在更有意义。

for random_number, current_time,i in generator():
    previous_last_price = mynumber
    mynumber = mynumber + (random_number*0.0001)
    #print (random_number*0.01)
    if mynumber >high_price: #new one
        high_price = mynumber
    if mynumber <low_price: #new one
        low_price = mynumber
    last_price = mynumber

    if keyfunc(current_time,1) != previous_reftime1min: #new one
        print mynumber,",",i, current_time,",", keyfunc(current_time,1),",", previous_reftime1min,",", open_price,",", high_price,",", low_price,",", last_price
        wrtr.writerow([mynumber, i,current_time, keyfunc(current_time,1), previous_reftime1min, open_price, high_price, low_price, last_price])    
        myfile.flush() # whenever you want, and/or
        open_price = previous_last_price
        high_price = mynumber
        low_price = mynumber
        last_price = mynumber
        previous_reftime1min = keyfunc(current_time,1)

【问题讨论】:

  • 你有什么问题?
  • 我编辑了问题
  • 缩进是怎么回事...?
  • 如果您需要在输入范围内多次重复此计算,则可以使用for 循环。您可以清理代码并将其放入 for 循环中的函数调用中,但对于不一定那么重要的小脚本。
  • 我知道这看起来很愚蠢,但我从来不明白如何在网站上保留 indetation,我点击“代码”它说在这里输入代码,然后我粘贴我的代码,我应该做其他事情吗?

标签: python function variables


【解决方案1】:

这是脚本的可能结构的一些伪代码,基于我所了解的你想要它做什么。

def check_price(random_number,last_price):
  new_price = do_some_logic() #do your logic
  write(new_price) #some abstract code to write your output to a file
  return new_price

price=some_initval
  while True:
    g=get_new_random_number()
    price=check_price(g,price)
    sleep(desired_period)

这里没有使用 for 循环,而是使用了 while 循环。我的理解是,您打算将此程序用作持续运行的守护程序,每分钟左右醒来,检查一些数据(例如当前价格)并运行计算。 while True 确保程序会重复执行此操作,直到您将其杀死。

【讨论】:

  • 我相信我找到了答案,这很难解释,但如果我将 myhigh_price 更改为以频率为键的字典,它似乎会帮助我继续使用它。无论如何感谢您的帮助。
猜你喜欢
  • 2015-12-15
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
相关资源
最近更新 更多