【问题标题】:Nested Lists- Python嵌套列表 - Python
【发布时间】:2018-11-19 13:51:43
【问题描述】:

我需要编写执行以下操作的 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] 或为cherry_field[1][0] 打印cherry1 或为cherry_filed[1][1][0] 打印cherry2 等,我可以打印cheery1,但我不是确定如何使用 while 循环遍历这些元素。

【问题讨论】:

标签: python list nested


【解决方案1】:

我认为这应该适合你。请检查一下。

使用 While 循环:

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]

使用扁平化(和递归):

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

【讨论】:

  • 如果我必须使用 flatten(和递归),怎么办?
【解决方案2】:

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

#!/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)

【讨论】:

  • 你的答案是否包括列表理解?
  • 我刚刚在各种嵌套列表上进行了测试,做了一些小改动,到目前为止它似乎对所有内容都有效。这就是递归的优势。
  • 比如它也可以做这个列表:cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!', None] ]]],'cherry5']
  • 您使用递归的答案很好,我的问题是您是否使用列表共理解。
  • 嗯,不。回顾 OP 的问题,我没有看到这个要求。
猜你喜欢
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
相关资源
最近更新 更多