【问题标题】:Reading current iterator value without incrementing in Python读取当前迭代器值而不在 Python 中递增
【发布时间】:2016-01-02 16:01:49
【问题描述】:

我正在编写一个具有两种不同状态的程序(英尺和米之间的可逆单位转换器),程序中的几个函数取决于当前状态(交替 itertools.cycle() 迭代器的当前值)。用户可以调用reverse函数来切换当前状态和反转计算转换函数。

目前,我使用 next(currentstate) 来返回迭代器的下一个值,如下所示:

self.currentstate = cycle(range(2))    

def reverse(self):
    if next(self.currentstate) == 0:
        self.feet_label.grid(column=2, row=2, sticky=tk.W)
    if next(self.currentstate) == 1:
        self.feet_label.grid(column=2, row=1, sticky=tk.W)

def calculate(self, *args):
    if next(self.currentstate) == 0:
        # convert feet to meters
    if next(self.currentstate) == 1:
        # convert meters to feet

不幸的是,每当调用函数并计算 if 语句时,循环迭代器都会由 next 运算符递增,并且下一次调用将产生不同的结果。计算函数可能会在同一状态下被多次调用,因此我想要某种方式来检索迭代器的当前值,而无需修改或增加运算符。

def calculate(self, *args):
    if currentvalue(self.currentstate) == 0:
        # convert feet to meters
    if currentvalue(self.currentstate) == 1:
        # convert meters to feet

我发现了一个非常丑陋的解决方法,涉及在每个 if 语句中调用 next(currentvalue) 两次以重置二进制值。这可能是编写这样的两态程序的一种非常糟糕的方式,但似乎应该有一种方法可以做到这一点。我对 Python 很陌生,也可能不完全理解迭代器的基本理论。

谢谢

【问题讨论】:

    标签: python iterator next itertools


    【解决方案1】:

    听起来您不应该在这里使用迭代器。您应该使用必须明确更改状态的东西。将这一切包装在自己的类中可能会更好。

    class StateMachine(object):
    
        STATE_ON = 1
        STATE_OFF = 0  # this could be an enum maybe?
    
        def __init__(self, starting_state=0):
            self.state = starting_state
    
        def self.change_state(self):
            if self.state = self.STATE_ON:
                self.state = self.STATE_OFF
            else:
                self.state = self.STATE_ON
    

    现在,无论您在何处使用状态机,都必须显式更改状态。

    statemachine = StateMachine()
    
    def calculate(*args):
        if statemachine.state == statemachine.STATE_ON:
            do_something
        if statemachine.state == statemachine.STATE_OFF:
            do_something_else
    
    def switch_state(*args):
        do_something  # and...
        statemachine.change_state()
    

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2012-07-03
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 2010-09-16
      相关资源
      最近更新 更多