是否將任何項目添加到外部列表的最後一個嵌套列表中,是一種很好的緊湊方式。 即:如何添加一個項目在python中的最後一個外部列表的嵌套列表?
a=[1,2,[3,4,[5,6]]]
後,我想7插入我的名單,成爲
a=[1,2,[3,4,[5,6,7]]]
是否將任何項目添加到外部列表的最後一個嵌套列表中,是一種很好的緊湊方式。 即:如何添加一個項目在python中的最後一個外部列表的嵌套列表?
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]]]
我無法理解s [ 1]概念 – curious
alist [-1]是列表的最後一個元素。創建s = [1,2,3,4]並查看s [-1] – foosion
'findlastlist'的不錯實現 – juliomalegria
如果你不是尋找一個通用的解決方案的更多信息:
>>> 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)
的函數,這在一定level
追加一個element
到alist
:
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
塊允許它處理空列表。
如果列表包含同一級別的多個列表,會發生什麼? – Acorn
我不明白你的問題。我尋求上述功能 – curious
最後一個元素總是列表還是最後一個列表後面有元素,即a = [1,2,[3,4,[5,6 ],7],8]?你想把它做到最深的清單還是最後一個清單,即應該在a = [1,2,[3,4,[5,6,#]]的第一個#或第二個# [7,#]]? –