【问题标题】:using time as a parameter in a conditional statement在条件语句中使用时间作为参数
【发布时间】:2020-09-18 02:49:13
【问题描述】:

我在字典中有一个 int(value),它在 while 循环中不断地被分配一个新值。 我正在尝试设置一个条件,如果 '(value) x 秒数,您将如何创建这段代码?

所以,我的想法是这样的:

from datetime import time

dict = {"special number": -0.5}

condition = 5

while true:

    if dict["special number"] < 0 'for more than' condition('%S'):

        del(dict)

提前致歉,我知道这个 if 陈述远非正确,只是为了举例。

最诚挚的问候

【问题讨论】:

  • 可能有很多方法可以做到这一点。想到的是每次更改值时将time.time()分配给一个变量,然后定期检查它。取决于你需要有多准确。使用python function call timeout 搜索可能会给您一些想法。
  • 或者创建一个可以保存您的值的类,并在值更改时开始倒计时 - 定期检查它是否超时..

标签: python dictionary datetime conditional-statements


【解决方案1】:

您需要自己记录时间。典型的解决方案可能如下所示:

  1. 当键第一次达到您的目标值时,启动一个计时器(即将当前时间存储在一个变量中)。
  2. 每次循环时,检查您的密钥的值。如果该值不再满足您的条件,请重置计时器。
  3. 如果计时器到期(即,已经过了足够的时间)且值满足您的条件,请执行您想要的操作。

我会用一个简单的状态机来做到这一点,比如:

state = 0
while True:
  if state == 0:
    if dict['special number'] < 0:
      start_time = time.time()
      state = 1
  elif state == 1:
    if dict['special number'] >= 0:
      # value failed condition before timer expired
      state = 0
    elif time.time() - start_time  > 5:
      perform_some_action()
      state = 0

【讨论】:

    【解决方案2】:

    不确定我是否正确。可能会有所帮助:

    import time
    
    dict = {"special number": -0.5}
    start_time = time.time()
    
    while True:
        if dict["special number"] < 0:
            print("number been less that 0 for {} seconds".format(time.time() - start_time))
        else:
            start_time = time.time()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2011-09-10
      相关资源
      最近更新 更多