简体   繁体   English

有人可以解释这个python代码如何不会给出错误

[英]can someone explain how this python code doesn't give an error

So I have inherited a rather crappy piece of code. 因此,我继承了一段相当糟糕的代码。 Indentation is as I found it. 缩进是我发现的。 Why does the else not throw an error? 为什么else不会引发错误? The code will never reach it as far as I understand. 据我所知,代码永远不会到达。

    for l in range(1,9):
        indexes = pickle.load(open('%s_%d.pkl'%(fc,l)))

        clusters_sum = sum([indexes[i]['count'] for i in indexes])
        print >> out, 'Lane %d: %d clusters PF.\n%8s  %9s  %5s' % (l,clusters_sum,'Index','Count','%')
        for i in sorted(indexes, key=lambda x: indexes[x]['name']):
            pct = indexes[i]['count'] and indexes[i]['count']/clusters_sum*100 or 0
            if pct < 0.06: continue
            print >> out, '%8s  %9d  %5.1f' % (indexes[i]['name'], indexes[i]['count'], pct)
        else: print >> out

See the documentation on else clauses on loops , this is valid syntax and the code within the else block is executed as long as there was no break , return , or uncaught exception within the loop. 请参阅有关循环的else子句的文档,这是有效的语法,只要循环中没有breakreturn或未捕获的异常,就会执行else块中的代码。

In this particular case the else clause will always be executed since none of the above conditions (other than an exception) can happen, so it is equivalent to the following: 在这种特殊情况下,将始终执行else子句,因为上述条件(除了异常)均不会发生,因此它等效于以下内容:

    for l in range(1,9):
        indexes = pickle.load(open('%s_%d.pkl'%(fc,l)))

        clusters_sum = sum([indexes[i]['count'] for i in indexes])
        print >> out, 'Lane %d: %d clusters PF.\n%8s  %9s  %5s' % (l,clusters_sum,'Index','Count','%')
        for i in sorted(indexes, key=lambda x: indexes[x]['name']):
            pct = indexes[i]['count'] and indexes[i]['count']/clusters_sum*100 or 0
            if pct < 0.06: continue
            print >> out, '%8s  %9d  %5.1f' % (indexes[i]['name'], indexes[i]['count'], pct)
        
        print >> out

for loops can have an else clause. for循环可以具有else子句。

From http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops : 来自http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Loop statements may have an else clause; 循环语句可以包含else子句; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. 当循环通过用尽列表而终止时(带有for)或条件变为假(具有while时),则执行此命令,但当循环由break语句终止时,则不执行该命令。

Since the loop doesn't contain a break statement, the else clause will always be executed. 由于循环不包含break语句,因此else子句将始终执行。

Not sure if you're not understanding the indentation (or lack thereof) on the else statement, or the fact that there is an "else" on the for loop. 不知道您是否不了解else语句上的缩进(或缺少缩进),或者for循环上是否存在“ else”。 If the former case... 如果是前一种情况...

The formatting is valid because print >> out is a "simple statement". 该格式是有效的,因为print >> out是一个“简单语句”。

Here is the grammar for a for statement : 这是for语句的语法:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

Notice that after the colon in the optional "else" block, it wants a " suite ", the grammar of which is... 请注意,在可选的“ else”块中的冒号之后,它需要一个“ 套件 ”,其语法为...

suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

So, it's possible in python to create a list of simple statements as an alternative to a block of statements. 因此,可以在python中创建一个简单语句列表,以代替语句块。 This is also valid... 这也是有效的...

for i in sorted(indexes, key=lambda x: indexes[x]['name']):
    pct = indexes[i]['count'] and indexes[i]['count']/clusters_sum*100 or 0
    if pct < 0.06: continue
    print >> out, '%8s  %9d  %5.1f' % (indexes[i]['name'], indexes[i]['count'], pct)
else: print >> out; print >> out; print >> out

and would be equivalent to... 相当于...

for i in sorted(indexes, key=lambda x: indexes[x]['name']):
    pct = indexes[i]['count'] and indexes[i]['count']/clusters_sum*100 or 0
    if pct < 0.06: continue
    print >> out, '%8s  %9d  %5.1f' % (indexes[i]['name'], indexes[i]['count'], pct)
else:
    print >> out
    print >> out
    print >> out

However, I think most people would prefer seeing the second syntax. 但是,我认为大多数人都希望看到第二种语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Code Academy(Python)代码实际上不在PyCharm中运行。 有人可以解释吗? - Code Academy (Python) code doesn't actually run in PyCharm. Can someone explain? 有人可以向我解释为什么这段代码不起作用吗? - Can someone explain to me why doesn't this piece of code work? 有人可以解释为什么 python 中的 var = input() 不起作用吗? - Can someone explain why var = input() in python doesn't work? 有人可以解释在Python代码段中如何处理数组和标量吗? - Can someone explain how arrays and scalars are handled in a Python code snippet 有人可以解释这个 python 代码中的“printtree”function 是如何工作的吗 - Can someone explain how the "printtree" function in this python code works 有人可以解释 python 中 staticmethod 的源代码是如何工作的吗 - Can someone explain how the source code of staticmethod works in python 我被告知 python 线程并不意味着我的代码并行运行,但它确实如此。 有人可以解释一下吗? - I'm told python threading doesn't mean my code runs in parallel, but it sort of does. can someone explain? 有人可以向我解释这段代码 - python 3 - can someone please explain to me this code - python 3 有人可以帮助解释这个python递归代码吗? - Can someone help explain this python recursive code? 有人可以解释 python 代码的这种行为吗 - Can someone explain this behaviour of python code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM