2013-04-08 30 views
16

我收到錯誤類型錯誤: '過濾器' 對象未標化的

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 ] 

我很抱歉這種類型的問題已經發布了很多次,但我對Python相當陌生,並沒有完全理解字典。我是否試圖以不應該使用字典的方式使用字典,或者我應該使用不使用字典的字典? 我知道修復可能非常簡單(儘管不是我),如果有人能指引我朝着正確的方向,我將非常感激。

我再次道歉,如果這個問題已經被回答

感謝,

克里斯。

我在Windows 7 64位上使用Python IDLE 3.3.1。

回答

25

filter() in python 3 does 不是返回一個列表,而是一個可迭代的filter對象。呼叫next()就可以拿到第一過濾項:

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

無需將其轉換爲一個列表,你只使用第一個值。

+9

這麼折騰時要記住這種語言是面向對象時,它的程序 - 爲什麼不'iterable.next()'的',而不是未來(迭代)'? – Basic 2014-03-11 12:19:40

+4

@基本:'.next()'是鉤子方法,'next()'是stdlib API。像'len()'與'.__ len __()','str()'與'.__ str __()'等一樣。在Python 3中,'.next()'方法被重命名爲'.__ next __() ';不給它一個特殊方法的名字是個錯誤。 'next()'(函數)還可以讓你指定一個默認值,以便在引發'StopIteration'時返回。 – 2014-03-11 12:21:49

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

使用list之前filter condtion然後它工作正常。對我來說,它解決了這個問題。

例如

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

,而不是

filter(lambda x: x%2!=0, mylist) 
相關問題