您不需要函数,只需将新列表分配到所需位置,它将替换以前的值。
l2 = ['Node_50',
['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']],
['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
]
lnew = ['Node_1', 'Node_40', 'Node_17']
之前
l2[1][3]
返回
['Node_20']
然后替换它
l2[1][3] = lnew
之后
l2[1][3]
返回
['Node_1', 'Node_40', 'Node_17']
这也可以通过函数
来完成
def myFUN(LIST, newLIST, indexes):
i,j = indexes
if i >= len(LIST):
print("list index (" + str(i) + ") out of range")
return
elif j >= len(LIST[i]):
print("list index (" + str(j) + ") out of range")
return
else:
LIST[i][j] = newLIST
return LIST
现在
myFUN(l2, lnew, indexes)
返回
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_1', 'Node_40', 'Node_17']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
但是
myFUN(l2, lnew, (4,1))
返回
list index (4) out of range
和
myFUN(l2, lnew, (1,25))
返回
list index (25) out of range
保持原列表不变
对于python3
def myFUN(LIST, newLIST, indexes):
res = LIST.copy()
i,j = indexes
if i >= len(LIST):
print("list index (" + str(i) + ") out of range")
return
elif j >= len(LIST[i]):
print("list index (" + str(j) + ") out of range")
return
else:
res[i][j] = newLIST
return res
在 python 2 中使用res = LIST[:] 或res=list(LIST)。现在
myFUN(l2, lnew, indexes)
返回
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_1', 'Node_40', 'Node_17']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
但 l2 保持不变
l2
返回
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]