首页 > 解决方案 > Python:如果 else 循环表现不同

问题描述

我正在尝试对数据框的特定组合执行操作,但我的代码运行不符合我的想法,我认为我没有做一些明显的错误。

years_list = []
check1 = 1
check10 = 1
r =30

for p in combinations(test4.index,r):
    den = np.mean(p)
    num = np.std(p)
    cv = num/den
    if (den >= 561 and den <= 570 ) :
       if(cv>=0.13 or cv <= 0.17 and check1):
          check1=0
          print("Combination 1 done")

    elif(den>=391 and den <= 400):
        if(cv>=0.13 or cv < 0.17 and check10):
           check10 = 0
           print("Combination 10 done")
    if(check1+check10==0)
        break

在这里,我正在更改 and 的值,check1以便check10循环0在 if else 条件内只进入一次,如果两个条件都满足,那么它会中断循环。 Test4.index是一个数据框,我猜应该是无关的信息。它的输出打印Combination 10 done多次,这是不应该发生的。我是在犯一些非常根本的错误还是更深层次的错误,我无法弄清楚?

编辑:我粘贴缩进错误,现在我正确粘贴了。

标签: pythonpython-3.x

解决方案


你的括号是错误的。

检查以下代码:

check1 = 0

if(True or True and check1):
    print("valid")
else:
    print("invalid")

输出:

有效的

如果要正确验证条件,请使用:

check1 = 0

if(True or True) and check1:
    print("valid")
else:
    print("invalid")

输出:

无效的

或者在你的情况下:

if(cv>=0.13 or cv < 0.17) and check10:
    check10 = 0
    print("Combination 10 done")

检查python中的运算符优先级以了解首先评估哪个运算符


推荐阅读