问题描述
我喜欢函数get,可以在其中提供默认值,但这仅适用于字典.
I like function get, where a default value can be supplied, but this work only on dictionary.
s=dict{}
s.get("Ann", 0)
我为list写了一些类似的东西.该功能在Python3.4中已经存在吗?
I wrote somethin similar for list. Does this function already exist in Python3.4?
def get(s, ind):
return len(s)>ind and s[ind] or 0
推荐答案
否,对于list
,不存在这样的内置方法.找出列表索引是否有效很简单,因此不需要任何功能.您只需将代码放入函数(或更具可读性的s[ind] if ind < len(s) else 0
)中,直接放入所需的两个或三个位置即可,这是完全可以理解的.
No, no such built-in method exists for list
s. It is trivial to find out if a list index is valid, so no function is needed. You could just put the code in your function (or the even more readable s[ind] if ind < len(s) else 0
) directly into the two or three places it's needed, and it would be perfectly understandable.
(当然,您的代码假定ind
始终为正...)
(Of course your code assumes ind
is always positive...)
如果您确实想编写一个函数,请使其成为list
子类的方法.
If you do want to write a function, make it a method of a list
subclass.
这篇关于是否有“获取或默认"设置?访问列表的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!