Why doesn#39;t list have safe quot;getquot; method like dictionary?(为什么列表没有安全的“get?像字典一样的方法?)
问题描述
为什么列表没有像字典一样的安全get"方法?
<预><代码>>>>d = {'a':'b'}>>>d['a']'b'>>>d['c']键错误:'c'>>>d.get('c', '失败')'失败'>>>l = [1]>>>l[10]IndexError:列表索引超出范围最终它可能没有安全的 .get 方法,因为 dict 是一个关联集合(值与名称相关联)在不抛出异常的情况下检查键是否存在(并返回其值)效率低下,而避免异常访问列表元素(如 len 方法非常快)..get 方法允许您查询与名称关联的值,而不是直接访问字典中的第 37 项(这更像您对列表的要求).
当然,你可以自己轻松实现:
def safe_list_get (l, idx, default):尝试:返回 l[idx]除了索引错误:返回默认值您甚至可以将它添加到 __main__ 中的 __builtins__.list 构造函数中,但这将是一个不太普遍的更改,因为大多数代码不使用它.如果您只是想将它与由您自己的代码创建的列表一起使用,您可以简单地继承 list 并添加 get 方法.
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
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
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.
这篇关于为什么列表没有安全的“get"?像字典一样的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么列表没有安全的“get"?像字典一样的方
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
