next() 可以返回迭代器的下一个值,在有些时候可以让代码更优雅。
比如要返回列表中第一个大于5的数字,如果没有则返回0
a = [1,3,6]
next((i for i in a if i > 5),0)
# output: 6
a = [1,3,4]
next((i for i in a if i > 5),0)
# output: 0
next() 第二个参数是设置,在没有下一个元素时返回该默认值。
next() 可以返回迭代器的下一个值,在有些时候可以让代码更优雅。
比如要返回列表中第一个大于5的数字,如果没有则返回0
a = [1,3,6]
next((i for i in a if i > 5),0)
# output: 6
a = [1,3,4]
next((i for i in a if i > 5),0)
# output: 0
next() 第二个参数是设置,在没有下一个元素时返回该默认值。