python - 在 Python for ... 循环中测试空迭代器

标签 python exception iterator conditional-statements

以下代码基于this recipe .然而,配方的关键点——它提供了一种在迭代器为空时中断迭代器迭代的方法——在这里似乎不起作用,而是以以下不受欢迎的方式表现:

  1. 如果 get_yes_no_answer() == False 并且迭代器中还有两个或更多项,则跳过 next_choice,而不是在下一次迭代中选择。
  2. 如果 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/

相关文章:

python - 我可以让 Python 准确地告诉我哪个字符导致错误吗?

android - 如何在 ionic 应用程序(cordova/phonegap)中获得完整的异常堆栈跟踪而不是一行?

java - 迭代器越界

python - pyQt5:无法连接 QSpinBox::valueChanged(int)

python - 解释 pandas DataFrame join 的工作原理

python - 如何将包含属性的 CSV 文件链接到 Python 类?

python - Python中的字符串slugification

java - java串口异常

java - 为什么 CopyOnWriteArrayList 需要写入和读取操作的副本?

c++ - 这个模板代码有什么问题?