python - 如果不在列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22833893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:46:56  来源:igfitidea点击:

python - if not in list

pythonlistfor-loopnotin

提问by Boosted_d16

I have two lists:

我有两个清单:

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

I have to work with some code I have inherited which looks like this:

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

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

How can I work with the code above to tell me that 'civic' is not in mylist?.

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

This would've been the ideal way to do it but I cant use it, don't ask me why.

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

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

Outcome:

结果:

civic

采纳答案by Santosh Ghimire

How about this?

这个怎么样?

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

回答by Will

Your code should work, but you can also try:

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

    if not item in mylist :

回答by Jose Manuel

You better do this syntax

你最好做这个语法

if not (item in mylist):  
    Code inside the if

回答by Yury Wallet

if I got it right, you can try

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

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