首页 > 解决方案 > 删除列表中的单词 - 循环故障

问题描述

我编写了一个简单的 for 循环,用于检查一个列表中的所有单词是否都在一个更大的列表中。这是在这里找到的练习题 。

我不明白为什么我的函数无法正确执行 - 运行它后,示例列表“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")

标签: pythonlist

解决方案


在循环中,您从列表中删除元素,然后word查看缩减列表的元素。

使用以下命令复制for循环行中的列表note[:]

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)


推荐阅读