2013-01-18 3 views
6

:条件は、参照によりないのでリストの値をPythonで反復処理しながら変更しますか?例えば

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) 

上記のコードは何もしません。これを行う適切な方法は何ですか?

答えて

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] 

この2番目の解決策では、他の言葉で言えば、このリストに他の言及がある場合、それらは影響を受けません。あなたがしたい場合は、スライスの割り当てを使用してかなり簡単な場所で置換を行うことができます。

def update_condition(self, type, params): 
    self.conditions[:] = [helper(c,type,params) for c in self.conditions] 
+0

+1。突然変異型と非突然変異型のどちらの選択肢もきれいに説明できます(これらのケースでは通常3ページのテキストを書きません)。 – abarnert

+0

@abarnert - フィードバックいただきありがとうございます。一貫して良い答えを書いている人が素敵なメモを残すときはいつもいいです:) – mgilson

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] 
+0

'update_single_condition'がstaticmethodまたは普通の関数であることができると私には思えます。それ以外の場合は、良い答え+1。 – mgilson

関連する問題