python - 删除列表中的单词 - 循环故障
问题描述
我编写了一个简单的 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")
解决方案
在循环中,您从列表中删除元素,然后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)
推荐阅读
- c# - 如何在后面的代码中从 DataTemplate 创建控件实例
- javascript - 使用 Javascript 检测亮度级别
- oracle - 如何修复此错误“ORA-01843: not a valid month”
- javascript - 如何将 FileReader base64 分配给变量?
- python-3.x - 使用 setuptools 更改已安装文件的权限
- excel - VBA; 运行时错误 1004,无法定义此变量?
- java - Maven多模块项目打包错误
- javascript - 将单选值添加到两个值的乘积以创建总 jquery
- elasticsearch - 弹性 - 根据其值确定要查询的字段
- android - 可以自动更新付费应用的价格 - Playstore