我在python中开发一个函数.这是我的内容:
list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
Run Code Online (Sandbox Code Playgroud)
所以我希望我的清单在更换后变成这样
list = ['cow','banana','cream','mango']
Run Code Online (Sandbox Code Playgroud)
我正在使用这个功能:
def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
Run Code Online (Sandbox Code Playgroud)
它输出如下列表:
['cow', ['banana', 'cream'], 'mango']
Run Code Online (Sandbox Code Playgroud)
那么如何修改此函数以获得以下输出?
list = ['cow','banana','cream','mango']
Run Code Online (Sandbox Code Playgroud)
注意:我在这里找到了一个答案:用另一个列表的内容替换列表项, 但我不想在这里涉及字典.我还想修改我当前的功能,并保持简单直接.
这种方法相当简单,与@ TadhgMcDonald-Jensen的iter_replace()方法具有相似的性能(对我来说是3.6μs ):
lst = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
def replace_item(lst, to_replace, replace_with):
return sum((replace_with if i==to_replace else [i] for i in lst), [])
print replace_item(lst, to_replace, replace_with)
# ['cow', 'banana', 'cream', 'mango']
Run Code Online (Sandbox Code Playgroud)
这是使用itertools类似的东西,但速度较慢(5.3μs):
import itertools
def replace_item(lst, to_replace, replace_with):
return list(itertools.chain.from_iterable(
replace_with if i==to_replace else [i] for i in lst
))
Run Code Online (Sandbox Code Playgroud)
或者,这是使用两级列表理解(1.8μs)的更快方法:
def replace_item(lst, to_replace, replace_with):
return [j for i in lst for j in (replace_with if i==to_replace else [i])]
Run Code Online (Sandbox Code Playgroud)
或者这是一个简单易读的版本,速度最快(1.2μs):
def replace_item(lst, to_replace, replace_with):
result = []
for i in lst:
if i == to_replace:
result.extend(replace_with)
else:
result.append(i)
return result
Run Code Online (Sandbox Code Playgroud)
与此处的一些答案不同,如果有多个匹配项,这些答案将进行多次替换.它们比反转列表或重复将值插入现有列表更有效(python每次执行时都会重写列表的其余部分,但这只会重写列表一次).
在迭代它时修改列表通常是有问题的,因为索引会转移.我建议放弃使用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']
Run Code Online (Sandbox Code Playgroud)
首先,切勿使用 python 内置名称和关键字作为变量名称(将 更改为list)ls。
您不需要循环,找到索引然后链接切片:
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']
Run Code Online (Sandbox Code Playgroud)
在 python 3.5+ 中,您可以使用就地解包:
[*ls[:idx], *replace_with, *ls[idx+1:]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
539 次 |
| 最近记录: |