假设我有此列表:
lst = [1, 2, 3, 4]
,我想检查某个值是否满足条件,如果是,请修改该值。最好的方法是什么?就像清晰度和效率的结合。我想出了以下3种选择:
# option 1
for i, item in enumerate(lst):
if item == 2:
lst[i] = 7
# option 2
counter = 0
for i in lst:
if i == 2:
lst[counter] = 7
counter += 1
# option 3
for i in range(len(lst)):
if lst[i] == 2:
lst[i] = 7
答案 0 :(得分:0)
我建议混合使用列表理解和函数定义:
lst = [1, 2, 3, 4]
def replace(x,y=2,z=7):
"""Replace value if condition holds.
Keyword arguments:
x -- value to check for replacement
y -- x will be replaced if it has the value of y
z -- x will be replaced by z if x is equal to y
"""
if(x==y):
x=z
return x
lst = [replace(x,2,7) for x in lst]