簡體   English   中英

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

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

Thery是將項目添加到外部列表的最后一個嵌套列表中的一種簡便的緊湊方法嗎? 即:

a=[1,2,[3,4,[5,6]]] ,插入7后,我希望我的列表成為

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

您可以使用索引來引用最后一個內部列表:

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

或者,您可以編寫一個函數來查找最后一個內部列表:

>>> 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]]]

如果您不尋求一般解決方案:

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

如果這樣做,這是一個簡單的實現(有關用法,請參閱doctests):

一個函數,它返回列表的嵌套級別:

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)

的函數,即追加一個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

要測試它們,只需運行:

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

如果您需要常規解決方案,請嘗試以下操作:

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]]]

它以遞歸方式遍歷嵌套列表的最后一個元素,直到到達非列表對象為止。 在這一點上,您的價值始終如一。 try / except塊允許它處理空列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM