为什么列表没有安全的“获取"信息?像字典一样的方法? [英] Why doesn't list have safe "get" method like dictionary?
问题描述
为什么列表没有像字典一样安全的获取"方法?
Why doesn't list have a safe "get" method like dictionary?
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l = [1]
>>> l[10]
IndexError: list index out of range
推荐答案
最终它可能没有安全的.get
方法,因为dict
是一个关联集合(值与名称相关联),效率低下检查键是否存在(并返回其值)而不会引发异常,而避免异常访问列表元素非常简单(因为len
方法非常快). .get
方法允许您查询与名称关联的值,而不是直接访问字典中的第37个项目(这更像是您要查询的列表中的内容).
Ultimately it probably doesn't have a safe .get
method because a dict
is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len
method is very fast). The .get
method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).
当然,您可以轻松地自己实现此目的:
Of course, you can easily implement this yourself:
def safe_list_get (l, idx, default):
try:
return l[idx]
except IndexError:
return default
您甚至可以将其猴子补丁到__main__
中的__builtins__.list
构造函数中,但这将是不那么普遍的更改,因为大多数代码都没有使用它.如果您只想将此代码与自己的代码创建的列表一起使用,则可以简单地将list
子类化并添加get
方法.
You could even monkeypatch it onto the __builtins__.list
constructor in __main__
, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list
and add the get
method.
这篇关于为什么列表没有安全的“获取"信息?像字典一样的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!