如果我可能在python中有列表列表,如何替换某些元素?我只想改变个别元素
def replace_item(the_list,toBeReplaced,toBeReplacedBy):
for each_item in the_list:
if isinstance(each_item,list):
replace_item(each_item,toBeReplaced,toBeReplacedBy)
else:
if each_item == toBeReplaced:
each_item=toBeReplacedBy
return the_list
如果我有一个列表
[[2,3],[[2,3,5,6],2,6,3],[1,2]]
如果我想用零替换2,那么结果应该是
[[0,3],[[0,3,5,6],0,6,3],0,6,3,[1,0]]
答案 0 :(得分:0)
通过将toBeplacedBy分配给each_item,您不会更改the_list中的项目。这就是你如何做到的。
def replace_item(the_list,toBeReplaced,toBeReplacedBy):
for index,each_item in enumerate(the_list):
if isinstance(each_item,list):
replace_item(each_item,toBeReplaced,toBeReplacedBy)
else:
if each_item == toBeReplaced:
the_list[index]=toBeReplacedBy
return the_list