列出“查找和删除列表中的项目”

问题描述

现在,我正在使用列表,所以我创建了2个列表,因此基本上我在其中一个中搜索了不在第二个列表中的值,如果不存在,我想将其从列表中删除。但是结果并没有删除所有条目。

这是我所做的:

vocales = ["a","e","i","o","u"]
found = ['a','b','i','o','u','h','l',' ','c','m','e','s','t']
for i in found:
    if i not in  vocales:
        print(i,end=" ")
        print(i not in vocales,end=" ")
        found.remove(i)
        print(found)
        input("press enter to continue")

因此,在运行程序时,所有辅音都无法识别

这是结果:

b True ['a','t']
press enter to continue 
h True ['a','t']
press enter to continue 
  True ['a','t']
press enter to continue 
m True ['a','t']
press enter to continue 
s True ['a','t']
press enter to continue 

但是,如果我在运行代码时未从列表中删除任何值,它将识别所有字母。

vocales = ["a",end=" ")
        print(found)
        input("press enter to continue")

这是结果:

b True ['a','t']
press enter to continue 
l True ['a','t']
press enter to continue 
c True ['a','t']
press enter to continue 
t True ['a','t']
press enter to continue 

所有辅音都可以识别,请问如何删除列表中未出现的项

解决方法

使用列表理解。

found = [x for x in found if x not in vocales]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...