c/c++语言开发共享python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

python 异常处理 StopIteration有StopIteration的情况没有StopIteration的情况有StopIteration的情况it = iter([1,2,3,4,5])while True:try:#获取下一个值x = next(it)print(x)except StopIteration:#遇到StopIteration就退出循环break这里退出while循环后还可以继续往下执行代码没有StopIteration的情况

python 异常处理 StopIteration

  • 有StopIteration的情况
  • 没有StopIteration的情况
  • 在next()中增加第二个参数
  • 执行一次next()输出多少个元素:一个
    • ==case one 以迭代器的形式==
    • ==case two 以列表形式作为输入: 不可以==
    • ==case three 以元组形式作为输入: 不可以==
    • ==case four : 利用iter + for 可以==
    • ==case five: (name for name in a)的数据类型到底是什么?:generator==

有StopIteration的情况

it = iter([1,2,3,4,5]) while True: 	try: 		#获取下一个值 		x = next(it) 		print(x) 	except StopIteration: 		#遇到StopIteration就退出循环 		break 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()
这里退出while循环后还可以继续往下执行代码

没有StopIteration的情况

it = iter([1,2,3,4,5]) while True:  	#获取下一个值 	x = next(it) 	print(x) 	# except StopIteration: 	# 	#遇到StopIteration就退出循环 	# 	break 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()
这里Traceback后就不能往下执行代码了

在next()中增加第二个参数

it = iter([1,2,3,4,5]) while True:  	#获取下一个值 	x = next(it,None) 	print(x) 	if x == None: 		break # 	# except StopIteration: # 	# 	#遇到StopIteration就退出循环 # 	# 	break print("hahahaha") 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

执行一次next()输出多少个元素:一个

case one 以迭代器的形式

it = iter([1,2,3,4,5]) # 以迭代器的形式 print(next(it,None)) 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

case two 以列表形式作为输入: 不可以

it = [2,1,3,4,5] print(next(it,None)) 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

case three 以元组形式作为输入: 不可以

it = (1,2,3,4,5) print(next(it,None)) 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

case four : 利用iter + for 可以

it = iter([1,2,3,4,5]) a = next((name for name in it),None) print(a) 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

case five: (name for name in a)的数据类型到底是什么?:generator

a = [1,2,3,4,5] b = [4,5,6,7,8] print(name for name in a if name not in b) c = (name for name in a if name not in b) print("the type of c:",type(c)) print("the output of next() function:",next(c,None)) 

python 异常处理 StopIteration 用来作为迭代器的输出停止/next()

c/c++开发分享python 异常处理 StopIteration 用来作为迭代器的输出停止/next()地址:https://blog.csdn.net/csdnhuizhu/article/details/107268520

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/595611.html

(0)
上一篇 2021年5月8日
下一篇 2021年5月8日

精彩推荐