Python if 语句效率 [英] Python if statement efficiency

查看:87
本文介绍了Python if 语句效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个朋友(低技能水平的休闲 python 脚本编写者)让我查看一些代码.我注意到他有 7 个单独的陈述,基本上是在说.

A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said.

if ( a and b and c):
    do something

语句 a,b,c 都测试了它们是否相等或缺少设置值.当我查看它时,我发现由于测试的性质,我可以将整个逻辑块重写为 2 个分支,这些分支的深度从不超过 3 级,并且很少超过第一级(将最罕见的发生测试排除在外)首先).

the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because of the nature of the tests, I could re-write the whole logic block into 2 branches that never went more than 3 deep and rarely got past the first level (making the most rare occurrence test out first).

if a:
    if b:
        if c:
    else:
        if c:
else:
    if b:
        if c:
    else:
        if c:

对我来说,从逻辑上讲,如果您进行更少、更简单的测试,而这些测试失败得更快并继续前进,那么它似乎应该更快.我真正的问题是

To me, logically it seems like it should be faster if you are making less, simpler tests that fail faster and move on. My real questions are

1) 当我说 if 和 else 时,如果 if 为真,else 是否会被完全忽略?

1) When I say if and else, should the if be true, does the else get completely ignored?

2) 理论上会

if (a and b and c)

if (a and b and c)

花费与三个单独的 if 语句一样多的时间?

take as much time as the three separate if statements would?

推荐答案

if 语句将跳过 else 括号中的所有内容,如果它的计算结果为真.应该注意的是,担心这类问题,除非每个程序执行数百万次,否则称为过早优化",应该避免.如果您的代码使用三个 if (a and b and c) 语句更清晰,则应保留它们.

if statements will skip everything in an else bracket if it evaluates to true. It should be noted that worrying about this sort of problem, unless it's done millions of times per program execution, is called "premature optimization" and should be avoided. If your code is clearer with three if (a and b and c) statements, they should be left in.

这篇关于Python if 语句效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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