gpt4 book ai didi

python - 迭代步骤和迭代传递在python中是否相同?

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:26 24 4
gpt4 key购买 nike

我想弄清楚什么是迭代步骤

wikipedia给出了关于迭代的解释

Iteration in computing is the technique marking out of a block of statements within a computer program for a defined number of repetitions. That block of statements is said to be iterated; a computer scientist might also refer to that block of statements as an "iteration".

python doc

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C) ...

考虑这个例子

#include <stdio.h>
int main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%d\n", i);
}
return 0;
}

显然总步数等于3。

因此,以下代码中的总步数等于 3。

>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i**2)

此代码在一个迭代步骤中打印 i^2,一个迭代步骤也称为迭代遍。

我的理解对吗?

最佳答案

在 C 中,迭代步骤是 for 的第三部分环形。在您的示例中,它是 i++ .每次执行循环时,该代码都会将值递增 1。 Python 在其 for 中没有内置等效概念循环,因为它们遍历可迭代对象,这些对象负责根据需要生成自己的值。并非所有可迭代对象都具有 C 风格中有意义的迭代步骤概念。

也就是说,与经典 C 风格最直接的类比 for Python 中的循环是一个 forrange 上循环目的。 range对象确实step , 尽管它默认为 1因此您可能并不总是看到它被明确指定。将 C 循环不必要地冗长地转换为 Python 将是:

for i in range(1, 4, 1): # the 1 last 1 could be omitted, since it's the default
...

迭代为 i 赋值从 1 开始在第一次迭代中(从第一个 1 传递到范围)。当值变为(或超过)4 时它停止(相当于 C 循环中的 <= 3 条件)。迭代步长为1 , 相当于 i++ .

当你在做其他奇怪的循环时,指定步骤更有用,比如从十到零倒数偶数:

for i in range(10, -1, -2): # 10, 8, 6, ..., 0
...

在 C 中会是:

for (i = 10; i > -1; i -= 2) {}

关于python - 迭代步骤和迭代传递在python中是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com