【发布时间】:2015-12-05 12:35:31
【问题描述】:
我的数据如下所示(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
使用这些数据,我需要编写一个条件语句,如果满足第 3 列和第 4 列中的两个条件,则在第 5 列打印单词“TRUE”,否则打印单词“FALSE” .
尝试使用python 嵌套“IF”语句,我编写了以下代码:
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"
这段代码的结果是“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 和here 以寻求解决问题的建议,并且代码仅适用于一种条件(例如,将所有“肯定”和“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
使用下面的建议,我尝试实现这一点,它只能正确找到第一个条件的情况。所有其他条件,无论它们是否为真,都被标记为假。我怎样才能让它识别所有 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"
【问题讨论】:
-
你熟悉
if ... elif ...这个概念吗? -
如果
oneScore == "positive"oneScore == "null"不可能是真的 -
你需要用or链接条件,没有嵌套的ifs:
if (a and b) or (c and d) or ...
标签: python python-2.7 if-statement conditional