2014-04-13 40 views
0

基本上,这是在一个类中附加另一个类的对象来列出自己。列表中有200个对象。所以基本上,如果我称自己[1],我会得到['约翰',['亚历克斯','罗布']。基本上'john'是指self.firstname,其他名称是指那里的组员。例如下面将打印每个对象的firstnames和groupmembers所有200个对象搜索列表以查看是否存在匹配python

for line in self: 
    print line.firstname 

for line in self: 
print line.groupmembers 

现在我创造的东西,通过所有的名字去和检查的名称。所以基本上,如果John有Alex和Rob作为成员,那么必须有另一个名字为Alex的对象和另一个名字为Rob的对象。所以说,没有与亚历克斯我想打印'不匹配'的名字的对象。这是我迄今为止所做的,但它没有做到它打算做的事情。

def name(self): 
      firstnames = [] 
      for item in self: 
       firstnames.append(item.firstname) 
      for item1 in self: 
       for i in item1.groupmembers: 
        if i not in hello: 
         print 'mismatch' 
+2

什么是'自己的项目'应该做的?你的类子类是否可迭代或以其他方式正确实现了该行为? –

+0

每个项目在自己(这有200个对象)是不同的学生对象。因此,我正在浏览每个对象,并将名称附加到列表中 – user3527972

+1

您的类是否可以子类化可迭代或以其他方式正确实现此行为?你不能通过'for'循环传递任何类的实例并使其工作。 –

回答

0

我不知道如果我准确地了解,但也许你可以使用包含

self[1].__contains__('Alex') 

这应该存在还是假的情况下返回true,否则。

+0

你是不是指自己的“Alex”? – Fury

1

好吧,首先,lineself是不好的变量名称。 self只应在类中使用,以用作调用或使用自己的变量的方式。

其次,你说这个自我列表中的每个值都包含像['John',['Alex', 'Rob']这样的值,但是接着你继续像使用类对象一样使用它......坦率地说,没有任何意义。

所以为了弥补这一点,我将假设它完成了类对象。我也会把自己重新命名为学校,而不是称自己的一个元素;行,这不会给读者没有信息..称之为学生!

我会假设你的类将开始寻找这样的:

class Student: 
    # having an empty default value makes it easy to see what types variables should be! 
    firstname = "" 
    groupmembers = [] 
    def __init__(self,firstname,groupmembers): 
     self.firstname = firstname 
     self.groupmembers = groupmembers 

然后,如果你有一个人名单,你可以通过它们,像这样循环..

>>>school = [Student("foo", ["bar", "that guy"]), 
      Student("bar", ["foo", "that guy"])] 

>>>for student in school: 
    print student.firstname 
    print student.groupmembers 

foo 
["bar", "that guy"] 
bar 
["foo", "that guy"] 

然后检查一个学生组成员是否在学校你可以添加一个功能到学生班

class Student: 
    # having an empty default value makes it easy to see what types variables should be! 
    firstname = "" 
    groupmembers = [] 
    def __init__(self,firstname,groupmembers): 
     self.firstname = firstname 
     self.groupmembers = groupmembers 

    def group_present(self, school): 
     # This is how you would get all the names of kids in school without list comprehension 
     attendance = [] 
     for student in school: 
      attendance.append(student.firstname) 
     # this is with list comprehension 
     attendance = [ student.firstname for student in school] 
     #compare group members with attendance 
     #note that I write student_name, not student 
     ## helps point out that it is a string not a class 
     for student_name in self.groupmembers: 
      if not student_name in attendance: 
       print "Group member '{}' is missing :o!! GASP!".format(student_name) 

我n空闲:

>>> school[0].group_present(school) 
Group member 'that guy' is missing :o!! GASP! 

希望帮助!