本文介绍了列表的get()的惯用python等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果字典中不存在键,则默认情况下在字典上调用get(key)将返回None.列表的惯用等效项是什么,例如,如果列表的大小至少为传入索引的大小,则返回该元素,否则返回None?
Calling get(key) on a dictionary will return None by default if the key isn't present in a dictionary. What is the idiomatic equivalent for a list, such that if a list is of at least size of the passed in index the element is returned, otherwise None is returned?
换句话说,此功能的惯用/紧凑版本是什么:
To rephrase, what's a more idiomatic/compact version of this function:
def get(l, i):
if i < len(l):
return l[i]
else:
return None
推荐答案
您的实现是突如其来样式.执行代码并捕获错误相反,这是pythonic:
Your implementation is Look Before You Leap-style. It's pythonic to execute the code and catch errors instead:
def get(l, i, d=None):
try:
return l[i]
except IndexError:
return d
这篇关于列表的get()的惯用python等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!