首页 > 解决方案 > 返回嵌套列表中元素的函数

问题描述

所以这是我得到的练习:

 def unflatten(ls):
    """returns elements in nested lists where the last element is None
    
    ls = list with string elements
    Examples:

    >>> unflatten(['Hello', 'world'])
    ['Hello', ['world', None]]
    >>> unflatten(['Hello'])
    ['Hello', None]
    >>> unflatten(['No', 'more', 'cherries', 'please!'])
    ['No', ['more', ['cherries', ['please!', None]]]]
    """
    """write your code here"""

所以我写了这个:

newls = []
    x = 0
    for x in range(len(ls)):
        if x==0:
            newls.append(ls[x])
        elif x == len(ls)-1:
            newls.append([ls[x], None])
        else:
            newls.append([ls[x], ])
    print(newls)

这仅对 2 个元素的列表是正确的 有人可以提出任何答案吗?

标签: pythonnested-lists

解决方案


也许我忽略了一些事情,但这种简单的递归方法还不够:

def unflatten(ls):
    if ls:
       return [ls[0], unflatten(ls[1:])]

>>> unflatten(['Hello', 'world'])
['Hello', ['world', None]]
>>> unflatten(['Hello'])
['Hello', None]
>>> unflatten(['No', 'more', 'cherries', 'please!'])
['No', ['more', ['cherries', ['please!', None]]]]

有很多方法可以以或多或少的可读/显式方式打扮这匹马,对于单行你可以包含一个条件表达式:

def unflatten(ls):
    if ls:
       head, *tail = ls
       return [head, unflatten(tail)]
    return None  # not necessary

def unflatten(ls):
    return [ls[0], unflatten(ls[1:])] if ls else None

推荐阅读