TypeError:“filter”对象不是subscriptab

2024-05-20 21:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到错误信息

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还不太熟悉,也不完全理解字典。我是想用不该用的方式来使用词典,还是应该用不该用的词典? 我知道解决方法可能很简单(尽管对我来说不是),如果有人能给我指出正确的方向,我将非常感激。

如果这个问题已经得到回答,我再次道歉

谢谢

克里斯。

我在Windows764位上使用PythonIdle3.3.1。


Tags: toimagenewindexiffilterlengthold
3条回答
image = list(filter(lambda i: abs(i[0] - ghost_x) < 1e-2 and abs(i[1] - ghost_y) < 1e-2, sheet))

python 3中的filter()不返回列表,而是返回一个iterablefilter对象。对它调用next()以获取第一个过滤项:

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

不需要将其转换为列表,因为您只使用第一个值。

使用listfilter条件之前,然后它工作正常。对我来说,它解决了这个问题。

例如

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

而不是

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

相关问题 更多 >