如何将元素添加到 Python 中的子列表?
问题描述
考虑列表中的列表
list1 = ["element1","element2",["subelement1","subelement2"]]
子元素1可以通过索引[2][0]访问
subelement1 can be accessed by index [2][0]
print (list1[2][0])
但是如果只能将两个参数传递给插入函数,我该如何在 [2][x] 位置插入元素.
But how can I insert elements at [2][x] position if only two parameters can be passed to insert function.
list.insert(index, element)
假设我想在 [2],[0]
处插入 "subelement0"
.这使得列表:
Lets say i want to insert "subelement0"
at [2],[0]
. That makes the list :
list1 = ["element1","element2",["subelement0","subelement1","subelement2"]]
解决方案
尝试如下插入元素到子列表:
Try to insert element to sublist as below:
list1[2].insert(0, 'subelement0')
print(list1)
# ['element1', 'element2', ['subelement0', 'subelement1', 'subelement2']]
相关文章