2012-10-02 33 views
0

我需要向WSHandler連接列表(Tornado,Python)添加更多值。我加入到像這樣self.connections.append(self)列表中的連接,但我需要添加更多的信息,像self.connections.append({'id': self, 'keyword' : ''})(後來發現當前self ID和更換關鍵字)。將dict(Python)列表中的值替換爲'id'對象

當我嘗試添加到基於列表在self對象(如self.connections[self].filter = 'keyword'),我得到TypeError: list indices must be integers, not WSHandler.

所以,我該怎麼辦呢?

編輯:設法找到像這樣合適的對象:

def on_message(self, message): 
    print message 
    for x in self.connections: 
     if x['id'] == self: 
      print 'found something' 
      x['keyword'] = message 
      print x['keyword'] 
      print x 

現在,如何從connections刪除整個字典?當然,self.connections.remove(self)不再有效。

回答

3

對於此用例,您不需要連接列表。將它存儲在對象本身中可能更容易。只需使用self.filter = 'keyword'即可。

否則:

for dict in self.connections: 
    if dict['id'] == self: 
     dict['keyword'] = 'updated' 

或者,如果你偏向於清晰簡潔:

for dict in [dict for dict in self.connections if dict['id'] == self]: 
    dict['keyword'] == 'updated' 

清除,可以用:

for dict in self.connections: 
    if dict['id'] == self: 
     self.connections.remove(dict) 
+0

謝謝。但它必須匹配連接列表中正確的ID。我如何確保它是正確的? – knutole

+0

啊,是的,我認爲你是對的 - 更容易存儲在對象本身。 – knutole

+0

基本上,如果您要查找的對象是'self',那麼就不需要根據它的'id'從連接中檢索它。在您的代碼片段中,您不會顯示存儲匹配ID的位置。哪裏是? –

1

由於self.connections是一個列表,你只能使用整數索引它(如錯誤所述)。 self這裏是WSHandler對象,不是的整數。

我不是龍捲風專家,所以你應該嘗試一下漢斯所說的。

如果您仍然需要按照您提及的方式進行操作,請嘗試:self.connections[self.connections.index(self)]以查找列表中的自我對象。

相關問題