gpt4 book ai didi

python - 在python的for循环中修改迭代器

转载 作者:行者123 更新时间:2023-12-03 22:58:15 35 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Scope of python variable in for loop

(10 个回答)


6年前关闭。




@ Padraic Cunningham Let me know if you want me to delete the question.



我是 python 新手。我想根据某些条件跳过一些迭代器值。这在 C 中很容易,但在 python 中我很难。

所以请帮助我理解为什么这里的代码循环了 100 次而不是 10 次。
 for i in range(100):
print i
i = i +10

编辑 :我知道可以选择更改 for 循环的步长。但是我对动态更改迭代器变量很感兴趣,就像我们可以在 C 中做的那样。好的,我明白了,python 中的 for 循环与 C 中的不同。简单的方法是使用 while 循环,我在我的代码中做到了它奏效了。谢谢社区!

最佳答案

for 循环遍历可迭代的 range(100) .

修改当前值不会影响可迭代对象中接下来出现的内容(实际上,您可以拥有任何可迭代对象;下一个值可能不是数字!)。

选项 1 use a while loop :

i = 0
while i < 100:
i += 4

Option 2 ,使用范围的内置步长参数:
 for i in range(0,100,10):
pass

这个例子可以更清楚地说明为什么你的方法没有多大意义:
for i in [1,2,3,4,5,'cat','fish']:
i = i + i
print i

这是完全有效的python代码(定义了字符串添加);修改可迭代对象需要一些不直观的东西。

See here for more information on how iterables work, and how to modify them dynamically

关于python - 在python的for循环中修改迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656017/

35 4 0
文章推荐: .htaccess - Htaccess 强制使用 WWW 进行多域
文章推荐: jquery - 当您将
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com