Convert from “For-loops” to “While-loops”

后端 未结 3 830
囚心锁ツ
囚心锁ツ 2020-12-12 06:15

I\'ve approached this question that I\'m struggling to solve. It\'s asking me to convert the code from \"for-loops\" to \"while-loops\":.

def print_names2(pe         


        
3条回答
  •  时光取名叫无心
    2020-12-12 06:37

    @Martijn's answer works for the test case given (a sequence of sequences of names), but it is not (and as far as I know, has never been) equivalent to the original for loop code, which works with iterables of iterables of names. An example of the latter, that works with the for loops but not the while loops, is

    def it_it_names():
        yield ['John', 'Smith']
        yield ['Mary', 'Keyes']
        yield ['Jane', 'Doe']
    

    Here is while-loop code that is essentially equivalent to the for loops.

    def pn_while(people):
        it = iter(people)
        try:
            while True:
                person = next(it)
                to_print = ""
                it2 = iter(person)
                try:
                    while True:
                        name = next(it2)
                        to_print += name + " "
                except StopIteration:
                    pass
                print(to_print)
        except StopIteration:
            pass
    
    pn_while(it_it_names())
    # prints
    John Smith 
    Mary Keyes 
    Jane Doe 
    

    Before 2.2, the while loop equivalent would use indexing by 0, 1, 2, ... instead of next() and catch IndexError instead of StopIteration. At least as of 1.4, len() was not used to stop the loop.

    It is perhaps worth noting that the body of the outer loop could be replaced with print(' '.join(person)). The only difference would be to not add a space at the end.

提交回复
热议问题