python - if not in list [duplicate]

2019-04-18 06:44发布

This question already has an answer here:

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

4条回答
▲ chillily
2楼-- · 2019-04-18 07:02

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)
查看更多
时光不老,我们不散
3楼-- · 2019-04-18 07:11

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item
查看更多
乱世女痞
4楼-- · 2019-04-18 07:16

You better do this syntax

if not (item in mylist):  
    Code inside the if
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-04-18 07:17

Your code should work, but you can also try:

    if not item in mylist :
查看更多
登录 后发表回答