Python 函数,该函数返回嵌套列表中的元素

Python 函数,该函数返回嵌套列表中的元素,python,nested-lists,Python,Nested Lists,这就是我得到的练习: 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]]

这就是我得到的练习:

 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个元素的列表
有人能给出一些答案吗?

递归解决方案看起来比迭代解决更好-买你仍然可以这样做:

def unflatten(ls):
    """returns elements in nested lists where the last element is None"""
    if isinstance(ls, list) and ls:
        # create list with first element if ls is not empty
        rv = [None if not ls else ls[0]]
        # remember the outermost list that we return
        rvv = rv
        # add an empty list at end
        rv.append([])
        for e in ls[1:]:
            # set rv to be the empty list at the end and add value
            rv = rv[-1]
            rv.append(e)
            # add another empty list
            rv.append([])
        # replace empty list at end by None
        rv[-1] = None    
        return rvv
    else:
        return ls # not a list - could raise an exception as well


print(unflatten(['Hello', 'world']))
print(['Hello', ['world', None]])

print(unflatten(['Hello']))
print(['Hello', None])

print(unflatten(['No', 'more', 'cherries', 'please!']))
print(['No', ['more', ['cherries', ['please!', None]]]])
输出:

['Hello', ['world', None]]
['Hello', ['world', None]]
['Hello', None]
['Hello', None]
['No', ['more', ['cherries', ['please!', None]]]]
['No', ['more', ['cherries', ['please!', None]]]]

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

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

下面是一个使用递归的简单解决方案:

def unflatten(lst):
    if not lst:
        return None
    return [lst[0], unflatten(lst[1:])]
或者更简短地说:

from functools import reduce

def unflatten(ls):
    return reduce(lambda v, w: [w, v], reversed(ls), None)

提示:以“由内而外”的相反方式进行<代码>a=[b,a]…我刚刚明白你的意思!!非常聪明的解决方案有效。。。为什么是dv?递归看起来比非递归的更好、更短是的,对我来说这看起来像是经典的递归,但是@deceze的解决方案是迭代的,而且非常好、简洁。如果我可以补充的话,在算法上比那些使用切片的递归解决方案(包括我的)更可靠。这是线性的,而我们的是二次的。。。
def unflatten(ls):
    val = None
    for word in reversed(ls):
        val = [word, val]
    return val
from functools import reduce

def unflatten(ls):
    return reduce(lambda v, w: [w, v], reversed(ls), None)