選項1:哪種風格是首選?
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
選項2:
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
這樣我就可以調用:
for c in ("China", "Japan"):
for f in (f1, f2):
print "%s => %s" % (c, f(c))
的選項,其一是確定鍵是否在目錄前手(f1),或者只是回退到例外(f2)。哪一個是首選?爲什麼?
除外:是惡業。始終要具體說明你對捕捉的興趣,在這種情況下KeyError – richo 2010-01-22 02:38:24
你選了一個不好的例子。明顯的答案既不涉及風格。 – Omnifarious 2010-01-22 02:47:34