我正在用 python 开发一个函数。这是我的内容:
list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
所以我希望我的列表在替换后变成这样
list = ['cow','banana','cream','mango']
我正在使用这个功能:
def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
它输出这样的列表:
['cow', ['banana', 'cream'], 'mango']
那么如何修改此函数以获得以下输出?
list = ['cow','banana','cream','mango']
注意:我在这里找到了答案:Replacing list item with contents of another list 但我不想在这方面涉及字典。我也只想修改我当前的功能,并保持简单明了。
最佳答案
在遍历列表的同时修改列表通常是有问题的,因为索引会四处移动。我建议放弃使用 for 循环的方法。
这是 while
循环比 for
循环更清晰、更简单的少数情况之一:
>>> list_ = ['cow','orange','mango']
>>> to_replace = 'orange'
>>> replace_with = ['banana','cream']
>>> while True:
... try:
... i = list_.index(to_replace)
... except ValueError:
... break
... else:
... list_[i:i+1] = replace_with
...
>>> list_
['cow', 'banana', 'cream', 'mango']
关于python - 在不使用字典的情况下用另一个列表的项目替换列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440360/