首页 > 解决方案 > 嵌套列表 - Python

问题描述

我需要编写执行以下操作的 Python 方法的主体:

1) 获取一个列表,其中 list[0] 是一个字符串,而 list[1] 是一个看起来相同的列表或 None

2)打印列表的每个字符串

我必须使用 while 循环,而不是使用列表理解或展平。

def pick_cherries_iter(field):
    """"e.g.
    >>> cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!', None]]]]]
    >>> pick_cherries_iter(cherry_field)
    cherry1
    cherry2
    cherry3
    cherry4
    Yay!!!"""

    _______________________
    _______________________
    _______________________
    _______________________
    while _________________:
        _______________________
        _______________________
        _______________________

我知道对于上面的示例,如果我为cherry_field[1][0] 打印cherry_field[0] 或cherry1 或cherry_filed[1][1][0] 等打印cherry1,我可以打印cheery1,但是我不知道如何使用 while 循环遍历这些元素。

标签: pythonlistnested

解决方案


我会递归地执行此操作,因为您无法知道元素是否为列表。

#!/usr/bin/python -E

cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!', None]]]]]
def print_list(field):
    i = 0
    list_length = len(field)
    while i < list_length:
     if field[i] is not None and type(field[i]) is not list:
        print(field[i])
     else:
        if field[i] is not None:
           print_list(field[i])
     i += 1
     if i < list_length and type(field[i]) is list:
        print_list(field[i])
        i += 1


def pick_cherries(field):
    if type(field) is list:
       print_list(field)

pick_cherries(cherry_field)

推荐阅读