python - 如何在给定代码中运行 if 循环

标签 python python-3.x

代码从 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 TestingBoolean 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/

相关文章:

python - os.environ.get() 使用 Google Cloud Functions 返回 None

c# - 在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组

python - 使用 pandas 将 BLOB 存储中的 .xlsx 转换为 .csv,无需下载到本地计算机

python - 推理后如何将标记化的单词转换回原始单词?

python - 这个 ZPT 模板有什么问题?

python - 如何在pyspark作业中为事件中心添加conf

python - SWIG:传递二进制数据失败

python - 处理抽象类中子类类型的循环导入

python - 我无法完全理解这行代码

python - Python 中带有条件的列表生成器