搜索列表以查看是否有匹配的python

2024-06-25 22:40:09 发布

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

基本上,这是在一个类中,该类将另一个类的对象追加到self列表中。列表中有200个对象。所以基本上如果我叫self[1],我会得到['John',['Alex','Rob']。基本上“约翰”指的是自己的名字其他的名字指的是这些小组成员。例如,下面将打印所有200个对象的每个对象的名字和组成员

  for line in self:
    print line.firstname

for line in self:
print line.groupmembers

现在我必须创建一个遍历所有名字并检查名字的东西。所以基本上,如果约翰有亚历克斯和罗伯作为成员,那么就必须有另一个名为亚历克斯的对象和另一个名为罗伯的对象。假设没有名字为Alex的对象,我想打印“mismatch”。这是我到目前为止,但它没有做它打算做的事。你知道吗

    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'

Tags: 对象inself列表forline成员firstname
2条回答

我不确定我是否完全理解,但也许您可以使用包含

self[1].__contains__('Alex')

如果存在,则返回true,否则返回false。你知道吗

好的,首先,lineself是错误的变量名。 self应该只在类中使用,作为调用或使用自己变量的方式。你知道吗

第二,你说这个self列表中的每个值都包含像['John',['Alex', 'Rob']这样的值,但是你继续把它当作类对象来使用。。。坦率地说,这是毫无意义的。你知道吗

为了解决这个问题,我将假设类对象已经完成了。我也会把self改名为school,而不是self的元素;line,它不会给读者带来任何信息。。叫它学生!你知道吗

我假设你的课开始是这样的:

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)

空闲时:

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

希望有帮助!你知道吗

相关问题 更多 >