以下代码基于this recipe .然而,配方的关键点——它提供了一种在迭代器为空时中断迭代器迭代的方法——在这里似乎不起作用,而是以以下不受欢迎的方式表现:
- 如果 get_yes_no_answer() == False 并且迭代器中还有两个或更多项,则跳过 next_choice,而不是在下一次迭代中选择。
- 如果 get_yes_no_answer() == False 并且迭代器中剩余的项目少于两个,my_func() 返回 None。
我如何确保:
- 如果 get_yes_no_answer() == False 并且迭代器中还有两个或更多项,next_choice 是否被 跳过?<
- 如果 get_yes_no_answer() == False 并且迭代器中还剩一个项目,my_func() 打印它并调用 get_yes_no_answer()?
- 如果 get_yes_no_answer() == False 并且迭代器中没有剩余项,是否会触发 except StopIteration 子句?
代码如下:
def my_func(choice_pattern, input):
# Search in input for some things to choose from.
choice_iterator = choice_pattern.finditer(input, re.M)
if not choice_iterator:
print "No choices. Exiting..."
sys.exit()
else:
# Show choices to the user. For each one, ask user for a yes/no response. If
# choice accepted, return a result. Otherwise show user next choice. If no
# choices accepted by user, quit.
for choice in choice_iterator:
print choice.group()
# get_yes_no_answer() returns True or False depending on user response.
if get_yes_no_answer():
return choice
else:
# Check if iterator is empty. If so, quit; if not, do something else.
try:
next_choice = choice_iterator.next()
except StopIteration:
print "No matches. Exiting..."
sys.exit()
else:
choice_iterator = itertools.chain([next_choice], choice_iterator)
最佳答案
你为什么要这样做?为什么不只是:
def get_choice(pattern, inpt):
choices = pattern.finditer(inpt, re.M)
if not choices:
sys.exit('No choices')
for choice in choices:
print(choice.group(0))
if get_yes_no_answer():
return choice
sys.exit('No matches')
我不知道你输入的长度是多少,但我怀疑这是否值得。
关于python - 在 Python for ... 循环中测试空迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1491957/