![](/img/trans.png)
[英]How to get the current value of a Python iterator - dereferencing an iterator without incrementing
[英]Reading current iterator value without incrementing in Python
我正在編寫一個具有兩個不同狀態的程序(在英尺和米之間的可逆單元轉換器),程序中的幾個函數取決於當前狀態(交替迭代的循環(循環)迭代器)。 用戶可以調用反向功能來切換當前狀態並反轉計算轉換功能。
目前,我使用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語句,循環迭代器都會被下一個運算符遞增,下一次調用將產生不同的結果。 計算函數可能會在同一個狀態中多次調用,因此我想要一些方法來檢索迭代器的當前值而無需修改或增加運算符。
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的新手,也可能沒有完全理解迭代器的基礎理論。
謝謝
聽起來你不應該在這里使用迭代器。 你應該使用一些必須明顯改變狀態的東西。 將這一切包裝在自己的類中可能更好。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.