python - 在不使用字典的情况下用另一个列表的项目替换列表中的项目

标签 python list

我正在用 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/

相关文章:

list - F# - 复制列表的递归函数

python - 如何在 Matplotlib TextBox 小部件中设置光标位置?

python - 如何使用正则表达式解释字符串?

database - 如何将数据框保存为列表的元素,反之亦然?

python - 和/或 python 中 boolean 列表的元素明智

包含 shared_ptr 的 std::list 的 C++ 重载 []

python - 替换嵌套数组中的多次出现

python - 给我最高的元素

python - 动画文本函数仅适用于某些字符串

c# - 如何制作一个包含空隙的列表<>?