在`python`中为同一个变量使用多个条件

oww*_*w14 2 python conditional if-statement python-2.7

我有如下所示的数据(4 列和制表符分隔):

AAA 123 null    0
AAA 124 null    1
BBB 234 null    0
CCC 235 negative    -2
CCC 345 negative    2
DDD 346 null    -1
EEE 456 positive    4
EEE 457 positive    0
Run Code Online (Sandbox Code Playgroud)

使用这些数据,我需要编写一个条件语句,如果满足第 3 列和第 4 列中的两个条件,则在第 5 列中打印单词“TRUE”,否则打印单词“FALSE”。

尝试使用 嵌套“IF”语句python,我编写了以下代码:

with open('infile.input', "r") as opened_file:
    for gLine in opened_file:
        print gLine
        oneID, twoID, oneScore, twoScore = gLine.split()
        if oneScore == "positive" and twoScore > 0:
            if oneScore == "null" and twoScore == 0:
                if oneScore == "neutral" and twoScore == 0:
                    if oneScore == "negative" and twoScore < 0:
                        print oneID, twoID, oneScore, twoScore, "TRUE"
        else:
            print oneID, twoID, oneScore, twoScore, "FALSE"
Run Code Online (Sandbox Code Playgroud)

此代码的结果是“FALSE”被分配给所有行,如下所示:

AAA 123 null    0   FALSE
AAA 124 null    1   FALSE
BBB 234 null    0   FALSE
CCC 235 negative    -2  FALSE
CCC 345 negative    2   FALSE
DDD 346 null    -1  FALSE
EEE 456 positive    4   FALSE
EEE 457 positive    0   FALSE
Run Code Online (Sandbox Code Playgroud)

. 我已经在这里这里寻找解决问题的建议,并且代码只在一个条件下工作(例如将所有“正”和“x>0”正确标记为 TRUE)。当我添加多个条件时,它无法达到我想要的结果,如下所示:

AAA 123 null    0   TRUE
AAA 124 null    1   FALSE
BBB 234 null    0   TRUE
CCC 235 negative    -2  TRUE
CCC 345 negative    2   FALSE
DDD 346 null    -1  FALSE
EEE 456 positive    4   TRUE
EEE 457 positive    0   FALSE
Run Code Online (Sandbox Code Playgroud)

使用下面的建议,我试图实现这一点,它只能正确地找到第一个条件的情况。所有其他条件,无论它们是否为真,都被标记为假。我怎样才能让它识别所有 4 个条件?

if  ((oneScore == "positive" and twoScore > 0) or
         (oneScore == "null" and twoScore == 0) or
         (oneScore == "neutral" and twoScore == 0) or
         (oneScore == "negative" and twoScore < 0)):
        print oneID, twoID, oneScore, twoScore, "TRUE"
    else:
        print oneScore, twoScore, "FALSE"
Run Code Online (Sandbox Code Playgroud)

Blc*_*ght 5

听起来你想要or,而不是嵌套if语句。您测试的所有条件永远不可能同时为真,因此嵌套ifs(and在此上下文中的工作方式)永远不会全部通过,让您的代码 print True

尝试:

if  ((oneScore == "positive" and twoScore > 0) or
     (oneScore == "null" and twoScore == 0) or
     (oneScore == "neutral" and twoScore == 0) or
     (oneScore == "negative" and twoScore < 0)):
    print bookID, ID, oneScore, twoScore, "TRUE"
Run Code Online (Sandbox Code Playgroud)

twoScore在您split从文件中读取的行之后,您仍然会遇到比较的问题,因为它将是一个字符串。int在进行比较之前,您需要在某个时候调用它。