6

例如:

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)

上面的代码什么都不做,因为条件不是引用。这样做的正确方法是什么?

4

2 回答 2

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]
于 2013-01-18T19:51:01.813 回答
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]
于 2013-01-18T19:45:38.100 回答