2016-11-20 37 views
0

我嘗試獲取列表中的對象實例的索引。我不知道如何在沒有for循環的情況下做到這一點。Python從列表中返回類的實例

如果有人能指示我正確的方向,而不是循環它。

我發現該列表具有任何()函數的實例,但無法從中獲取索引。

我試圖澄清我的問題。如果任何() - fucntion可以找到該列表(self.data)具有對象的實例。 any() - 函數只返回true/false。有沒有函數或方法來獲取該實例的索引,以便我可以調用它。

和代碼:

class MyClass: 

    def __init__(self, f): 
     self.data = [] 
     self.f = open(f, "rb") 
     self.mod = sys.modules[__name__] 

    def readFile(self): 
     f = self.f 
     try: 
      self.head = f.read(8) 
      while True: 
       length = f.read(4) 
       if length == b'': 
        break 
       c = getattr(self.mod, f.read(4).decode()) 
       if any(isinstance(x, c) for x in self.data): 
        index = self.data.index(c) #Problem is here 
        self.data[index].append(f.read(int(length.hex(), 16))) 
       else: 
        obj = c(data=f.read(int(length.hex(), 16))) 
        self.data.append(obj) 
       f.read(4) #TODO check CRC 
     finally: 
      f.close() 
+0

也許你應該在init中設置'self.data = []'而不是在類級別? –

+0

你能提供一個你正在閱讀的示例文件嗎? – urban

+0

好點,@JohnZwinck。代碼僅用於學習目的,如果有任何目的或評論我做錯了,我很高興聽到他們的消息。 – Evus

回答

2

enumerate是去這裏的路。

... 
c = getattr(self.mod, f.read(4).decode()) 
found = [ (i, x) for (i,x) in enumerate(self.data) if isinstance(x, c) ] 
if len(found) > 0: 
    index, val = found[0] 
    ... 
+1

不錯的,但我認爲你需要'if isinstance(x,c)'來存放'c'的實例到'found'中(也缺少'''') – urban

+0

@urban:Oups!我只是忘記了表達式的結尾:-(。謝謝你的注意。 –

+0

@SergeBallesta謝謝你,正是我一直在尋找的東西。 – Evus

1

着眼於獲取對象的實例及其在self.data列表索引:

# ... 

# This gives you back a class name I assume? 
c = getattr(self.mod, f.read(4).decode()) 

# The following would give you True/False ... which we don't need 
# any(isinstance(x, c) for x in self.data) 

# Now, this will return _all_ the instances of `c` in data 
instances = [x for x in self.data if isinstance(x, c)] 


if len(instances): 
    # Assuming that only 1 instance is there 
    index = self.data.index(instances[0]) 
    # ??? What do you append here? 
    self.data[index].append() 
else: 
    obj = c(data=f.read(int(length.hex(), 16))) 
    self.data.append(obj) 

f.read(4) #TODO check CRC