你可以使用enumerate
:
def update_condition(self, type, params):
for i,condition in enumerate(self.conditions):
condition_loaded = json.loads(condition)
if condition_loaded['type'] == type:
condition_loaded['params'] = params
self.conditions[i] = json.dumps(condition_loaded)
但是,总的来说,使用辅助函数和列表推导,这些东西会更干净一些:
def helper(condition,type,params)
loaded = json.loads(condition)
if loaded['type'] == type:
loaded['params'] = params
return json.dumps(loaded)
return condition
...
def update_condition(self, type, params):
self.conditions = [helper(c,type,params) for c in self.conditions]
应该注意的是,第二个解决方案不会更新列表 - 换句话说,如果您对此列表有其他引用,它们不会受到影响。如果需要,您可以使用切片分配非常轻松地进行替换:
def update_condition(self, type, params):
self.conditions[:] = [helper(c,type,params) for c in self.conditions]