【问题标题】:Can't find the boolean logic to make this work找不到布尔逻辑来完成这项工作
【发布时间】:2013-07-21 07:34:42
【问题描述】:

我试图做出这样的条件,如果数组中的 [0][0] 条目不等于 1 或 2,则程序会打印一条错误消息。我无法让它工作,我知道这是因为我无法让逻辑正确。

try:
    with open(input_script) as input_key:
        for line in input_key.readlines():
            x=[item for item in line.split()]
            InputKey.append(x)
    if InputKey[0][0] == 1 or 2:     #This is where my condition is being tested.
        print '.inp file succesfully imported' #This is where my success (or fail) print comes out.
    else:
        print 'failed'
except IOError:
    print '.inp file import unsuccessful. Check that your file-path is valid.'                                

【问题讨论】:

    标签: python if-statement boolean boolean-expression


    【解决方案1】:

    您的if 条件评估为:

    if (InputKey[0][0] == 1) or 2: 
    

    相当于:

    if (InputKey[0][0] == 1) or True: 
    

    将始终评估为True


    你应该使用:
    if InputKey[0][0] == 1 or InputKey[0][0] == 2:
    

    if InputKey[0][0] in (1, 2):
    

    请注意,如果您的InputKey[0][0]string 类型,您可以使用int(InputType[0][0]) 将其转换为int,否则它将与12 不匹配。

    除此之外,您的for 循环可以修改为:

    for line in input_key.readlines():         
        # You don't need list comprehension. `line.split()` itself gives a list
        InputKey.append(line.split())  
    

    【讨论】:

    • 我已经尝试了你的两个建议,但我得到了我设置的失败打印。我正在打印 InputKey[0][0] 值以确认它正在被正确读取并且它正在返回 1,但我仍然看到失败。
    • 你怎么知道它失败了?你得到什么输出?你期待什么?
    • 我上面有,只是我编辑了一个else 声明(基本上)“失败”。
    • 好吧,如果你的 InputKey[0][0] is one out of 1` 或 2,我发布的条件会起作用。如果没有,可能是其他地方出了问题。
    • 搞定了。我需要将我的整数期望用引号括起来,因为 python 最初会将它们解释为字符串(我假设)。
    【解决方案2】:

    if InputKey[0][0] == 1 or 2: 等同于:

    (InputKey[0][0] == 1) or (2)
    

    并且2 被认为是True (bool(2) is True),因此这个意志声明将始终为真。

    您希望 python 将其解释为:

    InputKey[0][0] == 1 or InputKey[0][0] == 2
    

    甚至:

    InputKey[0][0] in [1, 2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2018-03-11
      • 2021-01-06
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多