compass=[student.strip() for student in open("compassfeb8.txt",'U')]
roster=[student.strip() for student in open("feb4py.txt",'U')]
dropped=False
for name in compass:
if name not in roster:
print name
dropped=True
if not dropped:
print "Hooray! Nobody dropped."
此代码不起作用。但是,以下代码可以:
roster1=[student.strip() for student in open("jan24py.txt",'U')]
roster2=[student.strip() for student in open("feb4py.txt",'U')]
new_students=False
for name in roster2:
if name not in roster1:
print name
new_students=True
if not new_students:
print "There were no new students."
对于第一个代码块,我试图找出哪些学生仍然是我们班级网站上的用户,但不在大学的官方名单上,所以我们可以从课堂网站上删除它们。
第二个代码块检查我们是否有新学生。
这非常令人尴尬,但我无法弄清楚在粘贴我的代码时如何缩进。(我将在未来几周内学习HTML。)但是,我相信所有的缩进都是正确的。
答案 0 :(得分:1)
您不仅更改了变量名称,还更改了语句的嵌套。在for
和if
语句中翻转不起作用的变量名称。
答案 1 :(得分:0)
你可以尝试这样的事情。创建设置名称,然后使用set.difference功能查找新的\已删除的学生。
compass={student.strip() for student in open("compassfeb8.txt",'U')}
roster={student.strip() for student in open("feb4py.txt",'U')}
dropped_students = compass.difference(roster)
if not dropped_students:
print "Hooray! Nobody dropped."
roster1={student.strip() for student in open("jan24py.txt",'U')}
# roster2={student.strip() for student in open("feb4py.txt",'U')}
roster2 = roster
new_students = roster2.difference(roster1)
if not new_students:
print "There were no new students."