Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否有一个“问题”;获取或默认值";访问列表的方法?_Python_List_Python 3.x - Fatal编程技术网

Python 是否有一个“问题”;获取或默认值";访问列表的方法?

Python 是否有一个“问题”;获取或默认值";访问列表的方法?,python,list,python-3.x,Python,List,Python 3.x,我喜欢函数get,它可以提供默认值,但这只适用于字典 s=dict{} s.get("Ann", 0) 我写了一些类似的清单。Python3.4中是否已经存在此函数 def get(s, ind): return len(s)>ind and s[ind] or 0 否,lists不存在这样的内置方法。确定列表索引是否有效很简单,因此不需要函数。您可以将代码直接放在函数中(如果ind

我喜欢函数get,它可以提供默认值,但这只适用于字典

s=dict{}
s.get("Ann", 0)
我写了一些类似的清单。Python3.4中是否已经存在此函数

def get(s, ind):
    return len(s)>ind and s[ind] or 0

否,
list
s不存在这样的内置方法。确定列表索引是否有效很简单,因此不需要函数。您可以将代码直接放在函数中(如果ind,则更可读的
s[ind])所需的两个或三个位置,这是完全可以理解的

(当然,您的代码假定
ind
始终为正…)


如果您确实想编写函数,请将其设置为
列表
子类的方法。

没有类似于get for list的方法,但您可以使用默认值为0的
itertools.islice
next

from itertools import islice
def get(s, ind):
    return next(islice(s, ind, ind + 1), 0)
如果
ind
处的值为任何虚假值,如
0
None
False
等,则在代码中使用
和s[ind]
将返回默认值
0
。。这可能不是你想要的

如果要返回错误值的默认值并处理负索引,可以使用
abs

def get(s, ind):
    return s[ind] or 0 if len(s) > abs(ind) else 0

很清楚,你的意思是按值获取,对吗?您提议的实现令人困惑。为什么要使用
和s[ind]