C ++ for循环与Python for循环 [英] C++ for-loop vs. Python for-loop

查看:163
本文介绍了C ++ for循环与Python for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习数据挖掘课程时正在学习Python. 我当时正在制作一个for循环来制作一个嘈杂的数据文件,以进行平滑处理,但是我发现Python的for循环有一个我无法理解也无法解决的特殊之处.

I'm currently learning Python as I'm taking a data mining class. I was making a for-loop to make a noisy data file to do smoothing and I found a peculiarity on Python for-loop that I couldn't understand nor go around.

因此,我进行了此简单的测试C ++和Python代码. C ++可以,但是Python不能.

So I made this simple testing C++ and Python codes. C++ one works, but Python one doesn't.

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

The reason is that C++ allows arbitrary updates on the counter variable i within the for-loop block, but Python doesn't.

在Python代码上,我尝试通过在while循环内执行i += 1任意更新 i ,但是如果您查看At the first part of the loop, i = SOMETHING的输出,Python会在任意更新 > i 仅在for循环中的while循环中,但是在退出while循环时将其返回. (输出在底部的注释中)

On Python code, I try to update i arbitrarily by doing i += 1 within the while-loop, but if you look at the outputs for At the first part of the loop, i = SOMETHING, Python is arbitrarily updating the i only in the while-loop that's in the for-loop, but then reverts the value back when it exits that while-loop. (Outputs are in the comments at the bottom)

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

Why is that? Is it a scope issue? (Both C++ and Python are statically scoped) Is it because of their types? (I'm only familiar with statically-typed languages like C++ and Java, and not dynamically-typed languages like Python)

在Python上,似乎for循环实际上是一个带有按值返回参数 i 的函数,该函数忽略了函数内部对该参数进行的所有更改.

On Python, it seems like the for-loop is actually a function with return-by-value parameter i which ignores all the changes on the parameter that took place inside the function.

我尝试过:

  • 将计数器 i 设置为全局变量.
  • 使用range(0, len(input), *variable*),但是我仍然无法复制它.
  • 研究了是否可以通过在Python上使用静态变量或类似的排序来解决(我认为这无关紧要吗?)
  • Setting the counter i as a global variable.
  • using range(0, len(input), *variable*), but I still failed to replicate it.
  • Researched if it can be solved by using Static variable or similar sort on Python (I think it's irrelevant?)

在Python上,您将如何复制此C ++代码? 您能启发我为什么这些for循环的行为会有所不同吗?谢谢.

On Python, how would you replicate this C++ code? Could you enlighten me on why those for-loops behave differently? Thank you.

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

This is C++ code that's working correctly:

#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 ++代码:

And this is the Python code that's not working correctly, that I tried to make to replicate the C++ code:

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
"""

推荐答案

首先,复制c/c ++结构并不是解决问题的最佳方法.您将不可避免地要与该语言作斗争,而不是从其优势中受益.

First, replicating a c/c++ structure is not the best way to approach solving a problem. You will inevitably end up fighting against the language instead of benefiting from its strengths.

第二,要转换c/c ++ for循环,您必须意识到它实际上是在变相的一段时间:

Secondly, to convert a c/c++ for loop, you have to realize that it is actually a while in disguise:

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

由于Python for循环在每次迭代时都会覆盖控制变量(i),因此它们无法直接转换为在其代码块内修改控制变量的C/C ++循环.这些循环在Python中会转换为这种形式(笨拙且繁琐):

Because Python for loops override the control variable (i) at each iteration, they can not translate directly to C/C++ loops that modify the control variable within their code block. These kinds of loops translate to this in Python (which is unwieldy and cumbersome):

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

对于您的特定示例:

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

对您的代码进行更Python化的翻译看起来像这样:

A more pythonic translation of you code would look more like this:

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字符,因此除非您的输入来自非标准来源,否则最后一个单词可能会被删除

strings in python don't have a nul character at the end so the last word will likely be dropped unless your input comes from a non-standard source

Python具有内置功能,用于分隔字符串中的单词:

Python has a built-in function to separate words in a string:

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

这篇关于C ++ for循环与Python for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆