Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

python - Convert from "For-loops" to "While-loops"

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(people):
    for person in people:
        to_print = ""
        for name in person:
            to_print += name + " "
        print(to_print)

I've only managed to do the first half:

def print_names2(people):
    i = 0        
    while i < len(people[i]):
        print(i)
        i += 1

When I test it with:

print_names2([['John', 'Smith'], ['Mary', 'Keyes'], ['Jane', 'Doe']])

Returns:

0
1

Could someone clarify to me how to do it, as I'm pretty sure my approach to the answer is a bit far away.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are forgetting to index into people again; you are printing just the index. You also want to loop over all entries in people not just the names in the first sub-list:

def print_names2(people):
    i = 0        
    while i < len(people):
        print(people[i])
        i += 1

This only loops over the outer list. If you want to loop over the inner sublists, add a second while loop:

def print_names2(people):
    i = 0        
    while i < len(people):
        j = 0
        while j < len(people[i])
            print(people[i][j])
            j += 1
        i += 1

All this prints the names directly, and all names will end up on new lines rather than each sublist printed on one with a space in between. If you needed to replicate the string building, do so and not print until the inner while loop has ended:

def print_names2(people):
    i = 0        
    while i < len(people):
        to_print = ""
        j = 0
        while j < len(people[i])
            to_print += people[i][j] + " "
            j += 1
        print(to_print)
        i += 1

This now is closest to the original version with the for loops.

An alternative version could create copies of the lists and then remove items from those lists until they are empty:

def print_names2(people):
    i = 0        
    while i < len(people):
        person = list(people[i])
        to_print = ""
        while person:
            name = person.pop(0)
            to_print += name + " "
        print(to_print)
        i += 1

I left the outer loop using an index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...