开发者

What's the idiomatic python equivalent of get() for lists?

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 pa开发者_JAVA技巧ssed 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


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


If you expect l[i] to often not exist, then use:

def get(l,i):
    return l[i] if i<len(l) else None

If you expect l[i] will almost always exist, then use try...except:

def get(l,i):
    try:
        return l[i] 
    except IndexError:
        return None

Rationale: try...except is expensive when the exception is raised, but fairly quick otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜