首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >嵌套列表- Python

嵌套列表- Python
EN

Stack Overflow用户
提问于 2018-11-19 13:51:43
回答 2查看 175关注 0票数 0

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

1)接受一个列表,其中list是字符串,而list1要么是看起来相同的列表,要么没有

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

我必须使用时间循环,而不是使用列表理解或扁平。

代码语言:javascript
运行
复制
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或cherry1表示cherry_field1或cherry2 for cherry_filed1等,我可以打印cherry_field1,但是我不知道如何使用while循环来遍历这些元素。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-19 14:31:21

我觉得这应该对你有用。请检查一下。

使用While循环的

代码语言:javascript
运行
复制
def pick_cherry(field):
    """"e.g.
    >>> cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!',None]]]]]
    >>> pick_cherry(cherry_field)
    cherry1
    cherry2
    cherry3
    cherry4
    Yay!!!"""

    while field[1] != None:
        temp = field[0]
        print temp
        field = field[1]
    print field[0]

使用扁平(和递归)的

代码语言:javascript
运行
复制
flatten_field = []

def pick_cherry(field):
    if field[1] != None:
        flatten_field.append(field[0])
        pick_cherry(field[1])
    else:
        flatten_field.append(field[0])

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

    pick_cherry(field)

    for item in flatten_field:
        print item
票数 0
EN

Stack Overflow用户

发布于 2018-11-19 14:18:03

我会递归地这样做,因为您无法知道某个元素是否是一个列表。

代码语言:javascript
运行
复制
#!/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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53376092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档