用while循环打印嵌套列表

2024-09-30 01:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

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

打印输出(必需输出):

^{pr2}$

我的职能:

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

如何删除列表和字符串?在


Tags: toname列表forjohnpeoplesmithprint
3条回答

可以使用两个嵌套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 

people[name]给出了一个列表,这就是为什么在输出中看到list。您必须获取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))

相关问题 更多 >

    热门问题