不使用字典将列表中的项目替换为另一个列表中的项目 [英] Replacing an item in list with items of another list without using dictionaries
问题描述
我正在用python开发函数.这是我的内容:
I am developing a function in python. Here is my content:
list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
所以我希望替换后我的列表变成这样
So I want that my list becomes like this after replacement
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']
那么我如何修改此函数以获取以下输出?
So how do I modify this function to get the below output?
list = ['cow','banana','cream','mango']
注意:我在这里找到了答案:用内容替换列表项另一个列表但是我不想让字典参与其中.我也只想修改我当前的功能,并保持其简单明了.
NOTE: I found an answer here: Replacing list item with contents of another list but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.
推荐答案
首先,切勿使用python内置名称和关键字作为变量名称(将 list
更改为 ls
).
First off, never use python built-in names and keywords as your variable names (change the list
to ls
).
您不需要循环,找到索引然后链接切片:
You don't need loop, find the index then chain the slices:
In [107]: from itertools import chain
In [108]: ls = ['cow','orange','mango']
In [109]: to_replace = 'orange'
In [110]: replace_with = ['banana','cream']
In [112]: idx = ls.index(to_replace)
In [116]: list(chain(ls[:idx], replace_with, ls[idx+1:]))
Out[116]: ['cow', 'banana', 'cream', 'mango']
在python 3.5+中,您可以使用就地解压缩:
In python 3.5+ you can use in-place unpacking:
[*ls[:idx], *replace_with, *ls[idx+1:]]
这篇关于不使用字典将列表中的项目替换为另一个列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!