2013-04-08 14 views
16

ないエラーコードはTypeError: 'フィルタ' オブジェクトは、添字化

bonds_unique = {} 
for bond in bonds_new: 
    if bond[0] < 0: 
     ghost_atom = -(bond[0]) - 1 
     bond_index = 0 
    elif bond[1] < 0: 
     ghost_atom = -(bond[1]) - 1 
     bond_index = 1 
    else: 
     bonds_unique[repr(bond)] = bond 
     continue 
    if sheet[ghost_atom][1] > r_length or sheet[ghost_atom][1] < 0: 
     ghost_x = sheet[ghost_atom][0] 
     ghost_y = sheet[ghost_atom][1] % r_length 
     image = filter(lambda i: abs(i[0] - ghost_x) < 1e-2 and 
         abs(i[1] - ghost_y) < 1e-2, sheet) 
     bond[bond_index] = old_to_new[sheet.index(image[0]) + 1 ] 
     bond.sort() 
     #print >> stderr, ghost_atom +1, bond[bond_index], image 
    bonds_unique[repr(bond)] = bond 

# Removing duplicate bonds 
bonds_unique = sorted(bonds_unique.values()) 

そして

sheet_new = [] 
bonds_new = [] 
old_to_new = {} 
sheet=[] 
bonds=[] 

の次のブロックを実行しようとすると、私はエラーに

TypeError: 'filter' object is not subscriptable 

を受け付けております行に発生する

bond[bond_index] = old_to_new[sheet.index(image[0]) + 1 ] 

このタイプの質問は何度も投稿されていることをお詫びしますが、私はPythonをかなり新しくしており、辞書を完全に理解していません。私はそれを使用すべきではない方法で辞書を使用しようとしていますか、それとも私が使用していない場所で辞書を使用すべきですか? 修正はおそらく(私にとってではありませんが)非常に簡単であることを知っています。誰かが私を正しい方向に向けることができれば非常に感謝しています。この質問はすでに

おかげで、

クリスに答えてきた場合

はもう一度、私は謝罪します。

私はPython IDLE 3.3.1をWindows 7 64-bitで使用しています。

答えて

25

filter() python 3ではではないはリストを返しますが、繰り返し可能なのはfilterオブジェクトです。あなたが最初の値のみを使用して、リストに変換する必要はありません

bond[bond_index] = old_to_new[sheet.index(next(image)) + 1 ] 

最初フィルターアイテムを取得することにnext()を呼び出します。 filter condtion前

+9

この言語はオブジェクト指向であり、それは手続きだとき時に覚えているので、イライラする - なぜ 'iterable.next()'の代わりに次の 'の(反復可能ではありません) '? – Basic

+4

@Basic: '.next()'はフックメソッドで、stdlib APIの 'next()'です。 Python 3では '.next()'メソッドの名前が '.__ next __()'に変更されました。これは '' len() '' ';特別なメソッド名を付けないのは間違いでした。 'next()'(関数)では、 'StopIteration'が発生した場合に返すデフォルト値を指定することもできます。 –

2
image = list(filter(lambda i: abs(i[0] - ghost_x) < 1e-2 and abs(i[1] - ghost_y) < 1e-2, sheet)) 
0

使用listそれが正常に動作します。私にとっては、それは問題を解決しました。例えば

list(filter(lambda x: x%2!=0, mylist)) 

代わりの

filter(lambda x: x%2!=0, mylist) 
関連する問題