好吧,首先,line
和self
是不好的变量名称。 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!
希望帮助!
什么是'自己的项目'应该做的?你的类子类是否可迭代或以其他方式正确实现了该行为? –
每个项目在自己(这有200个对象)是不同的学生对象。因此,我正在浏览每个对象,并将名称附加到列表中 – user3527972
您的类是否可以子类化可迭代或以其他方式正确实现此行为?你不能通过'for'循环传递任何类的实例并使其工作。 –