python3中哪种方法更好?
我是python的初学者,我想知道哪种方法更好,假设我有下面的代码,在生产中应该使用哪种方法python3中哪种方法更好?,python,python-3.x,dictionary,try-catch,production,Python,Python 3.x,Dictionary,Try Catch,Production,我是python的初学者,我想知道哪种方法更好,假设我有下面的代码,在生产中应该使用哪种方法 d = {} d['a'] = set([0,1,2,0]) d['b'] = set([1,2,1,2]) 方法1: try: print(d['c']) except: print(set()) 方法2: try: ans = d['c'] except: ans = set() print(ans) 方法3: if 'c' in d.keys(): pr
d = {}
d['a'] = set([0,1,2,0])
d['b'] = set([1,2,1,2])
方法1:
try:
print(d['c'])
except:
print(set())
方法2:
try:
ans = d['c']
except:
ans = set()
print(ans)
方法3:
if 'c' in d.keys():
print(d['c'])
else:
print(set())
方法4:
if 'a' in d.keys():
ans = d['c']
else:
ans = set()
print(ans)
try
和except
子句是这样工作的。
执行try
语句下的代码。只要try
子句中发生异常,它就会跳转到except
语句。如果发生的错误与定义的异常相对应,则执行except
子句
这是您想要做的:
d = {}
d['a'] = set([0,1,2,0])
d['b'] = set([1,2,1,2])
try:
print(d['c']) #if this doesn't exist a KeyError is raised
#thus it immediately jumps to the except clause
except KeyError:
print("No such key in the dictionary")
但是如果你
print(d['a'])
没有异常发生,因此exception子句被跳过。对于这类事情,有dict.get
(或者defaultdict
,如果你有很多的话)。注意,这更像是一个问题;这里没有需要解决的问题。如果d.keys()中的'c',也不要使用,如果d中的'c:
做同样的事情。你想用ans做什么?程序员发表了以下主题:[Python-'if-foo-in-dict'vs'try:dict[foo]]([Python-'if-foo-in-dict'vs'try:dict[foo]])。那么这里就有这么多。事实上,你的问题是后者的翻版。