擅长:python、mysql、java
<p>使用字典的一个好处是,可以使用<code>in</code>操作符快速检查字典中是否有键。因此,可以用以下内容替换大的<code>if</code>/<code>elif</code>/<code>else</code>块:</p>
<pre><code>if choice in courses:
# do the output with choice as a key to the dictionaries
print("Course Number:", courses[choice])
print("Instructor:", instructors[choice])
print("Times:", times[choice])
else:
# choice is not a valid key to the dictionaries
print("Sorry, invalid course number")
</code></pre>
<p>这种编码方式在Python世界中被称为“三思而后行”(LBYL),因为在执行操作之前要检查要执行的操作(在字典中查找所选的类)是否有效。另一种样式(稍微高级一点)称为“请求宽恕比请求许可更容易”(EAFP),在EAFP中使用<code>try</code>和<code>except</code>子句来处理在某些异常情况下生成的异常。以下是如何以EAFP样式执行上述代码:</p>
<pre><code>try:
# try do the output unconditionally
print("Course Number:", courses[choice])
print("Instructor:", instructors[choice])
print("Times:", times[choice])
except KeyError:
# a KeyError is raised if choice isn't in the dictionaries
print("Sorry, invalid course number")
</code></pre>
<p>在这种情况下,这两种方法没有太大区别,但在某些情况下(如果检查情况是否有效需要大量时间),EAFP可能会更快,因为可能失败的操作已经在检查无效的情况(因此它可以引发适当的异常)。你知道吗</p>