List.append错误

时间:2015-08-22 00:28:49

标签: python list append

我在第17行和第34行收到错误; Comps.append(道具(看))"。

我正在尝试搜索"记录"对于某个项目的存在, 如果它不在列表中,则将其追加到最后。

有人可以帮忙吗?

class Props(object):
    def __init__(self, Name = None):
        self.Name = Name

a = '111'
Comps = []
Comps.append(Props('aaa'))
Comps.append(Props('bbb'))
Comps.append(Props(a))

look = 'ccc'
for Props in Comps:
    if look in Props.Name:
        print 'Found Duplicate - ', look
        break
    else:
        Comps.append(Props(look))        # TypeError: 'Props' object is not callable

for Props in Comps:
    print (Props.Name)

1 个答案:

答案 0 :(得分:2)

你在第17行之前重载了Props的含义,其中包含:

for Props in Comps:

由于Props是一个类,所以不应该将它用作迭代器。代替:

class Props(object):
    def __init__(self, Name = None):
        self.Name = Name

a = '111'
Comps = []
Comps.append(Props('aaa'))
Comps.append(Props('bbb'))
Comps.append(Props(a))

look = 'ccc'
for el in Comps:
    if look in el.Name:
        print 'Found Duplicate - ', look
        break
    else:
        Comps.append(Props(look)) 

for el in Comps:
    print (el.Name)

你也可以简化整个搜索/追加操作: 谢谢Jon!

if not any(el.Name == look for el in Comps): Comps.append(Props(look))
相关问题