删除超出我要求删除的元素?

时间:2014-03-02 15:23:27

标签: python tuples

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.")

当我去下课时,如果我输入Math 101,它不仅会删除Math类,还会删除Science类。知道为什么吗?关于“数学101”的任何内容都与“科学101”有关......

2 个答案:

答案 0 :(得分:1)

你需要改变这个:

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)

到此:

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

否则,在class_tup中找到dropped_class后,您将删除for循环其余部分中的每个class_tup[0]

作为旁注,您可能希望稍微处理一下您的命名约定(除其他外)。例如,tup1应该只是courses或类似的东西。

答案 1 :(得分:0)

这里还有另一个问题,那就是你在迭代它时从列表中删除元素。这会使解释器混乱,最终会跳过列表中的元素(尽管在此示例中无关紧要)。您可以通过制作列表的临时副本进行迭代来解决此问题:

for class_tup in tup1[:]:    # [:] makes a copy of the list
    if dropped_class in class_tup[0]:
        tup1.remove(class_tup)

我应该补充一点,在这种情况下它无关紧要的原因(但这是一个习惯的好习惯)是你只希望每个循环一个匹配。假设情况总是如此,您应该在break之后添加tup1.remove(class_tup)。同样,这里没有太大的区别,但会加快处理更长的列表。