C++ for-loop vs. Python for-loop

前端 未结 2 1503
粉色の甜心
粉色の甜心 2021-01-17 00:00

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-

2条回答
  •  别那么骄傲
    2021-01-17 00:22

    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.

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

    for (,,)
    {
        // your stuff
    }
    

    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):

    
    while :
         # your stuff
         
    

    for your particular example:

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

    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 
    

    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 has a built-in function to separate words in a string:

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

提交回复
热议问题