【发布时间】:2021-04-17 01:19:21
【问题描述】:
我正在尝试用包含所述元素的列表替换列表中的元素,例如:
list = ['cow','orange','apple','mango']
to_replace = 'orange', 'apple'
replace_with = ['banana','cream']
期望的输出:
['cow', ['banana', 'cream'], 'mango']
我已经阅读了1这个问题的答案并尝试了那里提到的功能:
def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
但它什么也没做。我还尝试了一个基本的相等函数:
list[1:3] = ['banana','cream']
但是两者都不起作用。有没有一个功能可以做到这一点?在我的实际问题中,list[1:3] 是一个迭代器,即list[i:i+2]。我不确定这是否会有所作为。要替换的项目将始终是连续的。
【问题讨论】:
标签: python list replace nested nested-lists