在python中,我们在字典中有get()方法来安全地获取值。有什么办法能做到这一点吗?
my_dict = {'fruit':'apple','colour':'black'}
my_dict.get('colour','None') #returns black
my_dict.get('veg','None') #returns None
my_list = ['apple','fish','blue','bottle','gold']
colour = my_list[2]
print(colour) #returns blue
value = my_list[7] #gives error. Expected: need to return default value as None.在我的例子中,my_list的长度不是constant.Values,而是在runtime.If中填充,我尝试获取不存在于my_list中的索引,它应该返回默认值为None。当列表没有请求索引时,如何获得默认值。?
发布于 2021-12-10 08:43:16
使用try-except块-
try:
value = my_list[7]
except:
print("Value doesn't exist")如果try语句出现错误,则切换到except块。
https://stackoverflow.com/questions/70301800
复制相似问题