栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python,为什么i = + 1不会导致无限循环?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python,为什么i = + 1不会导致无限循环?

Python for循环是基于迭代器的“ for-each”循环。每次迭代开始时都会重新分配迭代变量。换句话说,以下循环:

In [15]: nums = 1,2,5,8In [16]: for num in nums:    ...:     print(num)    ...:1258

等效于:

In [17]: it = iter(nums)    ...: while True:    ...:     try:    ...:         num = next(it)    ...:     except StopIteration:    ...:         break    ...:     print(num)    ...:1258

同样,以下循环是等效的:

In [19]: for num in nums:    ...:     print("num:", num)    ...:     num += 1    ...:     print("num + 1:", num)    ...:    ...:num: 1num + 1: 2num: 2num + 1: 3num: 5num + 1: 6num: 8num + 1: 9In [20]: it = iter(nums)    ...: while True:    ...:     try:    ...:         num = next(it)    ...:     except StopIteration:    ...:         break    ...:     print("num:", num)    ...:     num += 1    ...:     print("num + 1:", num)    ...:num: 1num + 1: 2num: 2num + 1: 3num: 5num + 1: 6num: 8num + 1: 9

请注意,C样式的for循环在Python中不存在,但是您始终可以编写while循环(c样式的for循环本质上是while循环的语法糖):

for(int i = 0; i < n; i++){    // do stuff}

等效于:

i = 0while i < n:    # do stuff    i += 1

请注意,不同之处在于,在这种情况下,迭代 取决于

i
# do stuff
,修改的任何内容
i
都会影响迭代,而在前一种情况下,迭代取决于
迭代器 。注意,如果我们确实修改了迭代器,则迭代会受到影响:

In [25]: it = iter(nums) # give us an iterator    ...: for num in it:    ...:     print(num)    ...:     junk = next(it) # modifying the iterator by taking next value    ...:    ...:15


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634048.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号