2016-11-20 18 views
0

リストのオブジェクトのインスタンスのインデックスを取得しようとしました。そして私はfor-loopなしでそれをする方法を知らない。リストからクラスのインスタンスを返すPython

誰かが私に正しい方向を教えてもらえれば、それをループしないでください。

リストにはany() - 関数のインスタンスがありますが、そのインデックスからインデックスを取得することはできません。

私は自分の問題を明確にしようとします。 any() - fucntionがそのリスト(self.data)を見つけることができる場合、objectのインスタンスを持ちます。 any() - 関数はtrue/falseのみを返します。私はそれを呼び出すことができるように、そのインスタンスのインデックスを取得する機能や方法がありますか?

とコード:

self.dataリスト内のオブジェクトとそのインデックスのインスタンスを得ることに焦点を当て
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

いいですが、 'found is'(' missing ')に' c'のインスタンスだけを格納する 'if isinstance(x、c)'が必要だと思います。 – urban

+0

@urban:Oups! –

+0

@SergeBallestaありがとう。ちょうど私が探していたもの。 – Evus

1

# ... 

# 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 
関連する問題