代码从 count=0
到 count=9。然后它不会进入其他 elif 代码。我在下面评论了哪个部分不起作用。我已经通过检查count的值尝试了很多次,但我仍然找不到代码不起作用的原因
count =0
for line in sys.stdin:
line = line.strip()
print(count)
if (count==0):
a = int(line) #no of series
count=1
elif(count==1): #2nd line 2 players 3 mtches
plyrs_mtchs=[]
plyrs_mtchs= line.split()
print(plyrs_mtchs)
count+=1 # #no of players , no of matches
elif(count==2 or count==6):
players.append(str(line))
print(players)
count+=1
elif(count==3,5 or count==7,9):
currenplyr = players[len(players)-1]
predict.append(line.split())
count+=1
elif(count==10 or count==11): #this code doesn't work
actual.append(line.split())
count+=1
elif(count==12): #this code doesnt work
actual.append(line.split())
count+=1
最佳答案
你的表情:
elif(count==3,5 or count==7,9):
并没有按照您的想法行事。你不是在测试 count
那里有 4 个可能值之一。 Python 将其视为 3 个不同的表达式组成一个元组:
count==3
5 or count==7
9
产生输出
(False, 5, 9)
如果count
不等于 3 和
(True, 5, 9)
如果是的话。 5 or <some other expression
将始终返回 5
因为它是一个非零数值,所以真实,而且 or
的另一边是什么并不重要运算符评估为 anymore。
具有 3 个元素的元组在 bool 上下文中始终为真,因为它是一个非空容器。因此,elif
如果在 if
之前,分支将总是匹配或 elif
测试失败。
参见 Truth Value Testing和 Boolean Operations有关如何进行 bool 测试和 or
的详细信息的部分工作。
使用 in
operator membership test相反:
elif count in {3, 5, 7, 9}:
如果 count
则测试为真有一个值在 4 个可能值的集合中。
关于python - 如何在给定代码中运行 if 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33319355/