例如:
def update_condition(self, type, params):
for condition in self.conditions:
condition_loaded = json.loads(condition)
if condition_loaded['type'] == type:
condition_loaded['params'] = params
condition = json.dumps(condition_loaded)
上述代码没有任何作用,因为条件不是通过引用。这样做的正确方法是什么?
答案 0 :(得分:14)
您可以使用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]
答案 1 :(得分:1)
您可以使用列表理解:
def update_single_condition(self, condition, type, params):
condition_loaded = json.loads(condition)
if condition_loaded['type'] == type:
condition_loaded['params'] = params
return json.dumps(condition_loaded)
def update_conditions(self, type, params):
self.conditions = [self.update_single_condition(c, type, params) for c in self.conditions]