【问题标题】:python: x is not this or this operatorpython: x 不是 this 或 this 运算符
【发布时间】:2015-01-26 05:43:37
【问题描述】:

有没有一种方法可以解决这个问题?

for file_name in listoffiles:
    if file_name != 'meta':
        if file_name != 'results':
            #this do this

我试过了,但没有达到我的预期:

for file_name in listoffiles:
    if (file_name != 'meta') or (file_name  != 'results'):
        #this do this

我做错了什么,正确的语法是什么?

【问题讨论】:

    标签: python for-loop operators conditional-statements


    【解决方案1】:

    您可以使用布尔运算符:

    if file_name != 'meta' and file_name != 'results':
    

    注意这里应该使用两个条件都必须为真!

    或使用(否定)成员资格测试:

    if file_name not in ('meta', 'results'):
    

    如果您使用的是 Python 3,尤其是如果您需要测试更多选项,请使用集合:

    if file_name not in {'meta', 'results'}:
    

    Python 3 识别集合文字并将其与代码一起存储为 frozenset() 常量对象,从而使测试非常高效。

    【讨论】:

    • 啊,那是我出错的地方,应该使用“and”而不是“or”!谢谢Martijn。
    【解决方案2】:

    尝试not in,将所有文件存储在tuple 中,然后检查它。 (根据 Martijn Pieters)

    for file_name in listoffiles:
        if file_name not in  ('meta', 'results'):
            # do something here
    

    【讨论】:

    • 不要使用列表; CPython 会在这里自动使用元组(不可变的可以变成常量),但你不应该指望它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多