2013-04-08 28 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) 
相关问题