sha*_*jin 17 python exception-handling exception
在我的Ruby应用程序中,我有一个哈希表:
c = {:sample => 1,:another => 2}
Run Code Online (Sandbox Code Playgroud)
我可以像这样处理表格:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
Run Code Online (Sandbox Code Playgroud)
我正在尝试用Python做同样的事情.我创建了一个新词典:
c = {"sample":1, "another":2}
Run Code Online (Sandbox Code Playgroud)
我无法处理nil值异常:
c["not-in-dictionary"]
Run Code Online (Sandbox Code Playgroud)
我试过这个:
c[:not_in_dictionery] is not None
Run Code Online (Sandbox Code Playgroud)
它返回一个异常,而不是False.我如何处理这个?
小智 34
在您的特定情况下,您应该这样做而不是与以下内容进行比较None:
"not_in_dictionary" in c
Run Code Online (Sandbox Code Playgroud)
如果您真的使用此代码,它将无法正常工作:
c[:not_in_dictionary] is not None
Run Code Online (Sandbox Code Playgroud)
Python没有:字典键的特殊关键字; 而是使用普通字符串.
Python中的普通行为是在请求缺少键时引发异常,并允许您处理异常.
d = {"a": 2, "c": 3}
try:
print d["b"]
except KeyError:
print "There is no b in our dict!"
Run Code Online (Sandbox Code Playgroud)
如果你想获取None一个值,如果缺少键,你可以使用dict's .get方法返回一个值(None默认情况下).
print d.get("a") # prints 2
print d.get("b") # prints None
print d.get("b", 0) # prints 0
Run Code Online (Sandbox Code Playgroud)
要检查密钥是否具有a中的值dict,请使用in或not in关键字.
print "a" in d # True
print "b" in d # False
print "c" not in d # False
print "d" not in d # True
Run Code Online (Sandbox Code Playgroud)
Python包含一个模块,允许您定义在正常使用时返回默认值而不是错误的字典:collections.defaultdict.你可以像这样使用它:
import collections
d = collections.defaultdict(lambda: None)
print "b" in d # False
print d["b"] # None
print d["b"] == None # True
print "b" in d # True
Run Code Online (Sandbox Code Playgroud)
注意混淆行为in.当你看到了,第一次的关键,它增加了它指向的默认值,所以它现在被认为是in的dict.
| 归档时间: |
|
| 查看次数: |
15484 次 |
| 最近记录: |