好吧,首先,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'循環傳遞任何類的實例並使其工作。 –