是否将任何项目添加到外部列表的最后一个嵌套列表中,是一种很好的紧凑方式。 即:如何添加一个项目在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,#]]? –