Python 删除元素删除超出我要求的内容?

Python 删除元素删除超出我要求的内容?,python,tuples,Python,Tuples,当我去辍学时,如果我输入数学101,它不仅会删除数学课,还会删除科学课。知道为什么吗?“数学101”与科学101部分无关 您需要更改以下内容: tup1 = [('Math 101', 'Algebra', 'Fall 2013', 'A'), ('History 201', 'WorldWarII', 'Fall 2013', 'B'), ('Science 301', 'Physics', 'Fall 2013', 'C'), ('English 401', 'Shakespeare',

当我去辍学时,如果我输入数学101,它不仅会删除数学课,还会删除科学课。知道为什么吗?“数学101”与科学101部分无关

您需要更改以下内容:

tup1 = [('Math 101', 'Algebra', 'Fall 2013', 'A'), 
('History 201', 'WorldWarII', 'Fall 2013', 'B'), 
('Science 301', 'Physics', 'Fall 2013', 'C'),
('English 401', 'Shakespeare', 'Fall 2013', 'D')]

choice = 0

while choice !=3:

print ("***********MENU************")
print ("1. Drop class")
print ("2. Print gradebook")
print ("3. Quit")

choice = (int(input("Please choose 1-2 to perform the function. \nPress 3 to exit the program. Thank you. \n")))
if choice == 1:
dropped_class = raw_input ("Which class would you like to drop? Enter class: ")
found = False
for class_tup in tup1:
    if dropped_class in class_tup[0]:
        found = True
    if found:
        tup1.remove(class_tup)
elif choice == 2:
    print tup1
elif choice == 3:
    print ("Exit program. Thank you.")
else:
    print ("Error.")
为此:

for class_tup in tup1:
    if dropped_class in class_tup[0]:
        found = True                  #  now found == True for the rest of the loop
    if found:
        tup1.remove(class_tup)
否则,在
class\u tup[0]
中找到已删除的
类后,将删除for循环其余部分中的每个
class\u tup


作为补充说明,您可能希望稍微改进一下命名约定(除其他事项外)。例如,
tup1
可能只是
courses
或类似的东西。

这里还有一个问题,就是在迭代列表时从列表中删除元素。这会混淆解释器,最终会跳过列表中的元素(尽管在本例中这并不重要)。您可以通过制作列表的临时副本来解决此问题:

for class_tup in tup1:                #  incidentally, tup1 is a list not a tuple
    if dropped_class in class_tup[0]:
        tup1.remove(class_tup)
        break  #  stops the iteration, which seems to be what you are trying to do

我应该补充一点,为什么在这种情况下这并不重要(但这将是一个很好的习惯),是因为你只希望每个循环有一个匹配。假设总是这样,您可能应该在
tup1.remove(class\u tup)
之后添加一个
break
。同样,它在这里不会有太大的区别,但会加快较长列表的处理。

您需要修复
while
循环的缩进。它已修复-粘贴的此代码中的缩进不正确。我在终端中运行它时没有错误,但我不明白的是,当我只要求删除数学时,科学被删除了。我在
while choice!=3:
没有缩进。同样的问题。Argh:(@TommyConnor哎哟,对不起。我无意中忽略了你的if子句。现在就修复它。@TommyConnor我很高兴它能工作!如果它对你有帮助,请随意。干杯。
for class_tup in tup1[:]:    # [:] makes a copy of the list
    if dropped_class in class_tup[0]:
        tup1.remove(class_tup)