python - if not in list [duplicate]

元气小坏坏 提交于 2019-12-06 17:00:37

问题


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?.

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

回答1:


How about this?

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



回答2:


Your code should work, but you can also try:

    if not item in mylist :



回答3:


if I got it right, you can try

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



回答4:


You better do this syntax

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


来源:https://stackoverflow.com/questions/22833893/python-if-not-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!