エラーが発生します
TypeError: 'filter' object is not subscriptable
次のコードブロックを実行しようとすると
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=[]
エラーは行で発生します
bond[bond_index] = old_to_new[sheet.index(image[0]) + 1 ]
この種の質問がSOに何度も投稿されていることをお詫びしますが、Pythonは初めてで、辞書を完全には理解していません。辞書を使用すべきでない方法で使用するのか、それとも使用していない場所で辞書を使用するのか?修正はおそらく非常に単純であることを知っていますが(私にとってはそうではありません)、誰かが私を正しい方向に向けることができれば感謝しています。
もう一度、この質問がすでに回答されている場合は申し訳ありません
おかげで、
クリス。
Windows 7 64ビットでPython IDLE 3.3.1を使用しています。
filter()
in python 3 does not return a list、but iterateable filter
object。Call next()
その上でfirstフィルターされたアイテムを取得します:
bond[bond_index] = old_to_new[sheet.index(next(image)) + 1 ]
最初の値のみを使用するため、リストに変換する必要はありません。
list
条件の前にfilter
を使用すると、正常に機能します。私にとってそれは問題を解決しました。
例えば
list(filter(lambda x: x%2!=0, mylist))
の代わりに
filter(lambda x: x%2!=0, mylist)
image = list(filter(lambda i: abs(i[0] - ghost_x) < 1e-2 and abs(i[1] - ghost_y) < 1e-2, sheet))