我试图使条件是如果数组中的[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.'
答案 0 :(得分:2)
您的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
将其转换为int(InputType[0][0])
,否则与1
不匹配}或2
。
除此之外,您的for
循环可以修改为:
for line in input_key.readlines():
# You don't need list comprehension. `line.split()` itself gives a list
InputKey.append(line.split())
答案 1 :(得分:2)
if InputKey[0][0] == 1 or 2:
与:
(InputKey[0][0] == 1) or (2)
2
被视为True
(bool(2) is True
),因此此语句将始终为True。
您希望python将其解释为:
InputKey[0][0] == 1 or InputKey[0][0] == 2
甚至:
InputKey[0][0] in [1, 2]