【问题标题】:Removing words in list - loop malfunction [duplicate]删除列表中的单词-循环故障[重复]
【发布时间】:2019-11-16 17:10:54
【问题描述】:

我编写了一个简单的 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")

【问题讨论】:

  • 我不知道绝对确定这是你的问题,但听起来肯定是这样。在迭代集合时,您无法可靠地更改集合的大小(例如从中删除)。这可能会导致奇怪的行为(比如元素被跳过)。更改为列表推导式,或者拥有第二个列表,它是原始列表的副本。
  • 实际上,this 是一个更好的骗子。
  • 如果你不想迭代你可以使用这样的东西:final = [word for word in mag1 if word not in note1]

标签: python list


【解决方案1】:

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

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

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)

【讨论】:

  • 是的,这就是我所说的。它不需要被复制。我已经编辑过了。
  • 刚刚看到重复的指示。随意关闭并删除它
  • 谢谢你,makis。一个问题:添加 [:] 实际上有什么作用?为什么它会起作用?
  • 阅读我回答的第一句话
  • 也在这里回答,[:] 复制列表。
【解决方案2】:

正如这个答案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")

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 2016-04-23
    • 2010-12-20
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多