Python-如果不在lis中

2024-05-23 13:53:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个清单:

mylist = ['total','age','gender','region','sex']
checklist = ['total','civic']

我必须处理一些我继承的代码,如下所示:

for item in mylist:
    if item in checklist:
        do something:

我如何使用上面的代码来告诉我“civic”不在mylist中?。

这本来是最理想的方法,但我不能用,别问我为什么。

for item in checklist:
    if item not in mylist:
        print item

结果:

civic

Tags: 代码inforageifitemgenderdo
3条回答

这个怎么样?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

您的代码应该可以工作,但您也可以尝试:

    if not item in mylist :

如果我做对了,你可以试试

for item in [x for x in checklist if x not in mylist]:
    print (item)

相关问题 更多 >