这是我编写的示例代码,用于在子列表的任意位置插入值。
import copy
List_of_Lists = [[1,2,3],[2,3,4],[4,4,4]]
List1 = ['Z','Y','X']
def Insert_List_of_Lists(List_X,index,value):
temp_list=copy.deepcopy(List_X)
if index<=len(temp_list):
for i in range(len(temp_list)):
temp_list[i].insert(index,value)
else:
for i in range(len(temp_list)):
temp_list[i].insert(len(temp_list),value)
print("Given index Out of range, value appended")
return(temp_list)
New_List_of_List = Insert_List_of_Lists(List_of_Lists,3,List1[0])
New_List_of_List
输出:
[[1, 2, 3, 'Z'], [2, 3, 4, 'Z'], [4, 4, 4, 'Z']]
当我们尝试从索引中添加一个值时:
X_list = Insert_List_of_Lists(List_of_Lists,8,'J')
X_list
输出:
Given index Out of range, value appended
[[1, 2, 3, 'J'], [2, 3, 4, 'J'], [4, 4, 4, 'J']]