相同的代码,不同的变量,不起作用?

2024-05-17 03:18:47 发布

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

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。)但是,我相信我所有的缩进都是正确的。你知道吗


Tags: 代码nameintxtnewforifcompass
2条回答

你可以试试这样的。按设置创建名称,然后使用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."

您不仅更改了变量名,还更改了语句的嵌套。将forif语句中的变量名翻转到不起作用的变量名上。你知道吗

相关问题 更多 >