【问题标题】:python - if not in list [duplicate]python - 如果不在列表中[重复]
【发布时间】:2014-05-15 01:27:42
【问题描述】:

我有两个列表:

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

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

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

如何使用上面的代码告诉我'civic'不在我的列表中?。

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

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

结果:

civic

【问题讨论】:

  • 它适用于我的 Python 2.7。 “if item not in mylist”或“if not item in mylist”都有效

标签: python list for-loop notin


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你最好这样做

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

    【讨论】:

    【解决方案3】:

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

        if not item in mylist :
    

    【讨论】:

    • 这对我来说最合乎逻辑并且有效!谢谢威尔 - 不知道为什么这是在底部。让我们把它推起来!
    【解决方案4】:

    这个怎么样?

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

    【讨论】:

    • 它适用于我的 Python 2.7。 “if item not in mylist”或“if not item in mylist”都有效
    • 其实首选语法是a not in b
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2021-11-03
    • 2011-10-23
    相关资源
    最近更新 更多