【问题标题】:C++ for-loop vs. Python for-loopC++ for 循环与 Python for 循环
【发布时间】:2020-04-10 13:19:48
【问题描述】:

我目前正在学习 Python,因为我正在学习数据挖掘课程。 我正在制作一个 for 循环来制作一个嘈杂的数据文件来进行平滑处理,我​​发现 Python for 循环有一个我无法理解也无法绕过的特性。

所以我做了这个简单的测试 C++ 和 Python 代码。 C++ 一个可以工作,但 Python 一个不行。

原因是 C++ 允许在 for 循环块中对计数器变量 i 进行任意更新,但 Python 不允许。

在 Python 代码中,我尝试通过在 while 循环中执行 i += 1 来任意更新 i,但如果您查看 At the first part of the loop, i = SOMETHING 的输出,Python 正在任意更新 i 仅在 for 循环中的 while 循环中,但在退出该 while 循环时将值恢复回来。 (输出在底部的 cmets 中)

这是为什么呢?是范围问题吗? (C++ 和 Python 都是静态作用域的) 是因为他们的类型吗? (我只熟悉 C++ 和 Java 等静态类型语言,不熟悉 Python 等动态类型语言)

在 Python 上,似乎 for 循环实际上是一个具有按值返回参数的函数 i,它忽略了函数内部发生的参数上的所有更改。

我试过了:

  • 将计数器 i 设置为全局变量。
  • 使用range(0, len(input), *variable*),但我仍然无法复制它。
  • 研究是否可以通过在 Python 上使用静态变量或类似排序来解决(我认为这无关紧要?)

在 Python 上,您将如何复制此 C++ 代码? 你能告诉我为什么这些 for 循环的行为不同吗?谢谢。

这是正常工作的 C++ 代码:

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    string input = "abc defg";
    string eachWord = "";

    for(int i = 0; i < input.length(); i++)
    {
        cout << "At the first part of the loop, i = " << i << " ." << endl;

        while(input[i] != ' ' && input[i] != '\0')
        {
            eachWord += input[i];
            i++;
        }

        cout << eachWord << endl;
        cout << "At the last part of the loop, i = " << i << " ." << endl << endl;
        eachWord = "";
    }
}

/*
Output:
At the first part of the loop, i = 0 .
abc
At the last part of the loop, i = 3 .

At the first part of the loop, i = 4 .
defg
At the last part of the loop, i = 8 .
*/

这是无法正常工作的 Python 代码,我试图复制 C++ 代码:

input = "abc defg"
eachWord = ''

for i in range(len(input)):
    print("At the first part of the loop, i = ", i, ".")
    while(input[i] != ' ' and input[i] != '\0'):
        eachWord += input[i]
        i += 1

    print(eachWord)
    print("At the last part of the loop, i = ", i, ".")
    print()
    eachWord = ''

"""
Output:
At the first part of the loop, i =  0 .
abc
At the last part of the loop, i =  3 .

At the first part of the loop, i =  1 .
bc
At the last part of the loop, i =  3 .

At the first part of the loop, i =  2 .
c
At the last part of the loop, i =  3 .

At the first part of the loop, i =  3 .

At the last part of the loop, i =  3 .

At the first part of the loop, i =  4 .
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    while(input[i] != ' ' and input[i] != '\0'):
IndexError: string index out of range
"""

【问题讨论】:

  • maxLen = len(input) 然后i = 0 然后while i &lt; maxLen: 并在循环结束时i+=1
  • 我认为您不应该在 Python 中复制您的 c++ 代码。 Python 风格不同,应该以不同的方式处理。例如:对于您的示例,您可以编写更多的一行/pythonic 代码。
  • “在 Python 上,for 循环似乎实际上是一个具有按值返回参数 i 的函数,它忽略了函数内部发生的参数上的所有更改。”这与实际发生的事情相差不远。在for 循环的每次迭代中,i 确实被range(len(input)) 的下一个值替换,而不管循环体中的i 发生了什么。
  • 如果你想拆分成单词,那么你只需要"abc defg".split(),你不需要创建所有的循环。
  • 谢谢你们!我只是“假设”不同语言的所有 for 循环都应该表现相同。

标签: python c++ for-loop


【解决方案1】:

首先,复制 c/c++ 结构并不是解决问题的最佳方法。你最终将不可避免地与语言抗争,而不是从它的优势中受益。

其次,要转换一个c/c++ for循环,你必须意识到它实际上是一个变相的while:

for (<initialization>,<condition>,<increment>)
{
    // your stuff
}

由于 Python for 循环在每次迭代时都会覆盖控制变量 (i),因此它们不能直接转换为修改代码块中控制变量的 C/C++ 循环。这些类型的循环在 Python 中转换为这种(笨重且繁琐):

<initialization>
while <condition>:
     # your stuff
     <increment>

对于您的特定示例:

i = 0
while i < len(input):
   # ...
   i += 1

你的代码的更 Pythonic 的翻译看起来更像这样:

eachword = ''
for character in input:
    if  character in [' ','\0']: # will drop last word because no \0 at end of strings
        print(eachword)
        eachword = ''
    else:
        eachword += character 

python 中的字符串末尾没有 nul 字符,因此最后一个单词可能会被删除,除非您的输入来自非标准来源

Python 有一个内置函数来分隔字符串中的单词:

for eachword in input.split():
    print(eachword)

【讨论】:

  • '受益于它的力量'...感谢您的重要建议!我想我必须以不同的方式思考以适应 Pythonic 风格。
【解决方案2】:

我看到的python有两个主要问题;

首先,for 循环的工作方式与 cpp for 循环不同:python 将重置 i 以通过范围,您在之前的循环中对 i 所做的操作将丢失。其次,python 在它的字符串上没有像 cpp 那样的终止字符:

input = "abc defg"
eachWord = ''

i = 0
while(i < len(input)):
    print("At the first part of the loop, i = ", i, ".")
    while(i < len(input) and input[i] != ' '):
        eachWord += input[i]
        i += 1

    print(eachWord)
    print("At the last part of the loop, i = ", i, ".")
    print()
    eachWord = ''
    i += 1

【讨论】:

  • 啊哈。现在我明白了为什么我之前看到的一些示例 Python 代码没有使用我认为更方便的 for 循环,而是在循环之外使用带有单独计数器声明的 while 循环。谢谢!
  • 但是为什么开发人员不会做出一致的 for 循环行为......?我对此感到非常困惑。
  • @HamInCheese Guido van Rossum(Python 的作者)创建了这种类型的 for 循环,因为它试图创建易于学习且代码易于阅读的语言。他因许多在其他语言中造成问题的因素而辞职。
  • 嗯,你可以看到这对于 python "for" 来说是更多的开销。它具有比 i 更多的状态,它必须在进行计算时记住整个范围(对于范围对象作为迭代器的开销并不大,但可以是列表等)。这通常是编程语言不同的原因。他们有不同的设计目标/对如何实现这些目标有不同的想法,或者在某些情况下太远而无法改变它。一般来说,python 会接受更多的开销以方便使用
猜你喜欢
  • 2022-10-20
  • 2021-10-15
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多