为什么列表没有安全的“get"?方法如字典? [英] Why doesn't list have safe "get" method like dictionary?

查看:23
本文介绍了为什么列表没有安全的“get"?方法如字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么列表没有像字典那样安全的get"方法?

<预><代码>>>>d = {'a':'b'}>>>d['a']'乙'>>>d['c']密钥错误:'c'>>>d.get('c', '失败')'失败'>>>l = [1]>>>升[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"?方法如字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆