在“python”中对同一变量使用多个条件`

2024-07-04 07:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据如下(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

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

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

^{pr2}$

此代码的结果是将“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

一。我已经查找了here和{a2}以寻求解决问题的建议,代码只使用一个条件(例如,将所有“肯定”和“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

使用下面的建议,我试图实现这一点,它只正确地找到第一个条件的情况。所有其他条件(无论它们是否为真)都被标记为false。我怎样才能识别出所有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"

Tags: and代码falsetrue条件nullbbbccc
3条回答

听起来您想要or,而不是嵌套的if语句。您测试的所有条件永远不可能同时为真,因此嵌套的if(在本文中类似于and)永远不会全部通过,让您的代码打印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"

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

比如说:

twoScore = int(twoScore)
cases = [
    oneScore == "positive" and twoScore > 0,
    oneScore == "null" and twoScore == 0,
    oneScore == "neutral" and twoScore == 0,
    oneScore == "negative" and twoScore < 0
]
state = any(cases) and "TRUE" or "FALSE"

它应该将数据与逻辑分开,并简化代码的维护。在

您应该使用if elif,而不是嵌套if,从您的代码中看,它从不打印“TRUE”

正确的逻辑应该是这样的

if oneScore == 'positive' and int(twoScore) > 0:
     print bookID, ID, oneScore, twoScore, "TRUE"

elif (oneScore == 'neutral' or oneScore == 'null') and int(twoScore) == 0:
    print bookID, ID, oneScore, twoScore, "TRUE"

elif oneScore == 'negative' and int(twoScore) < 0:
    print bookID, ID, oneScore, twoScore, "TRUE"

else:
    print bookID, ID, oneScore, twoScore, "FALSE"

相关问题 更多 >

    热门问题