通过 while 循环打印嵌套列表

printing a nested list by a while loop

我需要使用 while 循环打印嵌套列表。任何使用 for 循环都会受到惩罚。 我的函数输出与要求的输出不匹配。

例如:

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

打印出来(要求输出):

John Smith 
Mary Keyes 
Jane Doe

我的函数:

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

打印出来:

['John', 'Smith']
['Mary', 'Keyes']
['Jane', 'Doe']

如何删除列表和字符串?

people[name] 给出了一个列表,这就是您在输出中看到列表的原因。您必须获取 people[name] 列表的元素。

def print_names2(people):
    i = 0
    while i < len(people):
        print " ".join(people[i])
        i += 1
print '\n'.join([" ".join(i) for i in people])

将您的 print(to_print) 更改为 print(" ".join(to_print))

您可以使用两个嵌套的 while 循环:

def print_names2(people):
    i = 0    
    while i < len(people):
        sub_list = people[i]
        j = 0;
        while j < len(sub_list):       
            print(sub_list[j], end=' ')
            j += 1;
        i += 1


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