<p>好的,首先,<code>line</code>和<code>self</code>是错误的变量名。
<code>self</code>应该只在类中使用,作为调用或使用自己变量的方式。你知道吗</p>
<p>第二,你说这个self列表中的每个值都包含像<code>['John',['Alex', 'Rob']</code>这样的值,但是你继续把它当作类对象来使用。。。坦率地说,这是毫无意义的。你知道吗</p>
<p>为了解决这个问题,我将假设类对象已经完成了。我也会把self改名为school,而不是self的元素;line,它不会给读者带来任何信息。。叫它学生!你知道吗</p>
<p>我假设你的课开始是这样的:</p>
<pre><code>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
</code></pre>
<p>如果你有一张名单,你可以像这样在他们中间循环。。你知道吗</p>
<pre><code>>>>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"]
</code></pre>
<p>然后要检查学生组成员是否在学校,您可以向学生类添加一个函数</p>
<pre><code>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)
</code></pre>
<p>空闲时:</p>
<pre><code>>>> school[0].group_present(school)
Group member 'that guy' is missing :o!! GASP!
</code></pre>
<p>希望有帮助!你知道吗</p>