Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...