删除列表中的单词-循环故障

时间:2019-11-16 17:10:54

标签: python list

我编写了一个简单的for循环,用于检查一个列表中的所有单词是否都在较大的列表中找到。这是一个实践问题 here

我不明白为什么我的函数不能正确执行-运行它后,示例列表“ note2”中剩下的是['one','today'],因此似乎循环以某种方式跳过了这些话。这是为什么?!我从概念上不了解。

谢谢您的帮助。

示例列表(两对示例):

mag1=['two', 'times', 'three', 'is', 'not', 'four']
note1=['two', 'times', 'two', 'is', 'four']

mag2=['give', 'me', 'one', 'grand', 'today', 'night']
note2=['give','one','grand','today']

功能:

def checkMagazine(magazine, note):
    #Counter(note1).max
    for word in note:
        if word in magazine:
            magazine.remove(word)
            note.remove(word)
            #print(magazine)
            #print(note)
        #print(note)
    if len(note)>0:
        #ans="No"
        print("No")
    else:
        #ans="Yes"
        print("Yes")

2 个答案:

答案 0 :(得分:2)

在循环中,您从列表中删除了元素,然后word正在查看简化列表中的元素。

使用fornote[:]循环行中复制列表:

def checkMagazine(magazine, note):
    for word in note[:]:
        if word in magazine:
            magazine.remove(word)
            note.remove(word)

mag2=['give', 'me', 'one', 'grand', 'today', 'night']
note2=['give','one','grand','today']

checkMagazine(mag2, note2)

答案 1 :(得分:1)

如该答案https://stackoverflow.com/a/58718886/313935中所述,从循环内的列表中删除项目始终是徒劳的。您可以通过检查已在代码中注释掉的print语句的结果来发现自己(即,每次删除项目时列表中项目的位置都会改变)。

这是另一种方法:

def checkMagazine(magazine, note):    
    matches=0
    for word in note:
        if word in magazine:
            matches+=1

    if matches==len(note):
        print("Yes")
    else:
        print("No")