简体   繁体   English

如何在python外部列表的最后一个嵌套列表中添加项目?

[英]How to add an item at the last nested list of an outer list in python?

Is thery any nice compact way of adding an item to the last nested list of an outer list. Thery是将项目添加到外部列表的最后一个嵌套列表中的一种简便的紧凑方法吗? Ie: 即:

a=[1,2,[3,4,[5,6]]] and after the insertion of 7 i want my list to become a=[1,2,[3,4,[5,6]]] ,插入7后,我希望我的列表成为

a=[1,2,[3,4,[5,6,7]]]

You can use indexing to reference the last inner list: 您可以使用索引来引用最后一个内部列表:

>>> a=[1,2,[3,4,[5,6]]]
>>> a[2][2].append(7)
>>> a
[1, 2, [3, 4, [5, 6, 7]]]

Or you can write a function to seek out the last inner list: 或者,您可以编写一个函数来查找最后一个内部列表:

>>> def findlastlist(s):
    while s and isinstance(s[-1], list):
        s = s[-1]
    return s

>>> a=[1,2,[3,4,[5,6]]]
>>> findlastlist(a).append(7)
>>> a
[1, 2, [3, 4, [5, 6, 7]]]

If you don't look for a general solution: 如果您不寻求一般解决方案:

>>> a=[1,2,[3,4,[5,6]]]
>>> a[-1][-1].append(7)
>>> print a
[1, 2, [3, 4, [5, 6, 7]]]

If you do, here's a naive implementation (for usage, see the doctests): 如果这样做,这是一个简单的实现(有关用法,请参阅doctests):

A function, that returns the nesting level of a list: 一个函数,它返回列表的嵌套级别:

def nesting(alist, level=0):
    """ Get the nesting level of a list.

    >>> nesting([])
    0
    >>> nesting([1, 2])
    0
    >>> nesting([1, [2]])
    1
    >>> nesting([1, 2, [3, 4, [5, 6]]])
    2
    >>> nesting([1, 2, [3, 4, [5, 6]], [33, 44, [55, 66]]])
    2
    """
    try:
        alist[-1]
    except IndexError:
        return level
    except TypeError:
        return level - 1
    else:
        return nesting(alist[-1], level=level + 1)

A function, that appends an element to alist at a certain level : 的函数,即追加一个elementalist在一定的level

def append_nested(alist, element, level):
    """
    >>> x = []
    >>> append_nested(x, 'hello', nesting(x))
    ['hello']

    >>> x = [1, 2, 3]
    >>> append_nested(x, 'hello', nesting(x))
    [1, 2, 3, 'hello']

    >>> x = [1, 2, 3, [4, 5]]
    >>> append_nested(x, 'hello', nesting(x))
    [1, 2, 3, [4, 5, 'hello']]

    >>> x = [1, 2, 3, [4, 5], [7, 8]]
    >>> append_nested(x, 'hello', nesting(x))
    [1, 2, 3, [4, 5], [7, 8, 'hello']]

    >>> x = [1,2,[3,4,[5,6]]]
    >>> append_nested(x, 7, nesting(x))
    [1, 2, [3, 4, [5, 6, 7]]]

    >>> x = [1,2,[3,4,[5,6]]]
    >>> append_nested(x, 7, 0) # append to the 'root' list
    [1, 2, [3, 4, [5, 6]], 7]
    """
    z = alist
    for i in range(level):
        z = z[-1]
    z.append(element)
    return alist

To test them, just run: 要测试它们,只需运行:

if __name__ == '__main__':
    import doctest
    doctest.testmod()

If you need a general solution try this: 如果您需要常规解决方案,请尝试以下操作:

def last_inner_append(x, y):
    try:
        if isinstance(x[-1], list):
            last_inner_append(x[-1], y)
            return x
    except IndexError:
        pass
    x.append(y)
    return x

>>> x = [1,2,[3,4,[5,6]]]
>>> y = 7
>>> last_inner_append(x, y)
[1,2,[3,4,[5,6,7]]]

It recursively works through the final element of nested lists until it reaches something that is not a list. 它以递归方式遍历嵌套列表的最后一个元素,直到到达非列表对象为止。 At this point it sticks your value there. 在这一点上,您的价值始终如一。 The try / except block allows it to handle empty lists. try / except块允许它处理空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM