【发布时间】: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]