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

前端 未结 2 1478
粉色の甜心
粉色の甜心 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 (<initialization>,<condition>,<increment>)
    {
        // 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):

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

    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)
    
    0 讨论(0)
  • 2021-01-17 00:26

    There are two main problems with the python I see;

    Firstly the for loop does not work in the same way as the cpp for loop: python will reset i to go through the range, what you did with i inside the previous loops will be lost. Secondly python does not have a termination char on its strings like cpp does:

    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
    
    0 讨论(0)
提交回复
热议问题