在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的长度不是恒定的。正在运行时填充值。如果我试图获取my_list中不存在的索引,它应该返回默认值None。当列表没有请求索引时,如何获取默认值。?
使用try-except
块-
try:
value = my_list[7]
except:
print("Value doesn't exist")
如果try
语句有错误,它将切换到except
块