从"For-loops"转换为到"While-loops" [英] Convert from "For-loops" to "While-loops"

查看:70
本文介绍了从"For-loops"转换为到"While-loops"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解决了这个我正在努力解决的问题.它要求我将代码从"for循环"转换为"while循环":.

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)

我只完成了前半部分:

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']])

返回:

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.

推荐答案

您忘记了再次索引到people;您只打印索引.您还希望遍历people中的所有条目,而不仅仅是第一个子列表中的名称:

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

这仅循环遍历外部列表.如果要循环访问内部子列表,请添加第二个while循环:

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

所有这些都直接打印名称​​ ,所有名称都将以新行结尾,而不是将每个子列表打印在一个空格之间.如果需要复制字符串构建,请这样做,直到内部while循环结束后才打印:

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

现在它最接近具有for循环的原始版本.

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.

这篇关于从"For-loops"转换为到"While-loops"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆