马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zltzlt 于 2020-4-4 13:44 编辑
Python 实现 first()
上代码:
_def = object() # default value
def first(iterable, *, default=_def):
"""first(iterable, *, default) --> The first item of *iterable*, or *default* if *iterable* is empty"""
for i in iterable:
return i
if default is _def: # no default value was provided
raise ValueError('first() was called on an empty iterable, and no default value was provided.')
return default
print(first([3, 4, 6, 7])) # Out 3
print(first(range(5, 8))) # Out 5
print(first([], default=0)) # Out 0
print(first(())) # Error
如果代码有问题,欢迎在评论区指正 |