为什么python在for和while循环之后使用'else'? [英] Why does python use 'else' after for and while loops?

查看:34
本文介绍了为什么python在for和while循环之后使用'else'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解此结构的工作原理:

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print("Too big - I'm giving up!")
        break;
else:
    print("Completed successfully")

但我不明白为什么 else 在这里用作关键字,因为它表明只有在 for 块未完成时才运行有问题的代码,这与它的作用相反!无论我怎么想,我的大脑都无法从 for 语句无缝地前进到 else 块.对我来说,continuecontinuewith 会更有意义(我正在努力训练自己这样阅读).

But I don't understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for statement to the else block. To me, continue or continuewith would make more sense (and I'm trying to train myself to read it as such).

我想知道 Python 编码人员如何在脑海中(或大声朗读,如果您愿意)阅读此结构.也许我遗漏了一些可以让这些代码块更容易破译的东西?

I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?

推荐答案

即使对于经验丰富的 Python 编码人员来说,这也是一个奇怪的结构.当与 for 循环结合使用时,它的基本意思是在可迭代对象中找到一些项目,否则如果没有找到就……".如:

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
        break
else:
    print('No object found.')

但是无论何时你看到这个结构,更好的选择是将搜索封装在一个函数中:

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
    for obj in objects:
        if obj.key == search_key:
            return obj

或者使用列表推导式:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
    print('Found {}'.format(matching_objs[0]))
else:
    print('No object found.')

它在语义上不等同于其他两个版本,但在非性能关键代码中工作得足够好,无论您是否迭代整个列表都无关紧要.其他人可能不同意,但我个人会避免在生产代码中使用 for-else 或 while-else 块.

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

另请参见 [Python-ideas] 摘要....else 线程

这篇关于为什么python在for和while循环之后使用'else'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆