繁体   English   中英

x (> if bool else <) y

[英]x (> if bool else <) y

我正在寻找将 function 与不同运算符一起使用的逻辑。

有没有办法实现使用 boolean 来确定比较中的运算符的逻辑? 类似的东西

while df["column"][i + period] (> if bool_var else <=) min(df["column"])

编辑:任何人都可以明确地告诉我如何使用 operator 模块实现该逻辑吗?

while operator.gt(a, b) if bool_var else operator.eq(a, b): ?

为了避免if/else分支中的重复块,您需要做的就是根据operator模块创建的positive标志和比较运算符更改while语句:

from operator import eq, gt

def check_trends(df, set_lenght, positive=True, get_index=False):
    periods = []
    op = gt if positive else eq  # select operator
    
    for i in range(len(df.index)):
        period = 0
        while op(df["perc_btc"][i + period], min(df["perc_btc"])):
            if len(df.index) <= (i + period + 1):
                break
            period += 1
        if period > set_lenght:
            periods.append([i, period])
            if get_index:
                return [i, i + period]  # returns the last starting point
    return periods

另一种方法是进行两个单独的比较,每个比较都取决于newbool 在此示例中adf["column"][i + period]bmin(df["column"]

>>> newbool = True
>>> a = 4
>>> b = 5
>>> (a>b and newbool) or (a<=b and not newbool)
False
>>> newbool = False
>>> (a>b and newbool) or (a<=b and not newbool)
True
>>> a = 6
>>> (a>b and newbool) or (a<=b and not newbool)
False
>>> newbool = True
>>> (a>b and newbool) or (a<=b and not newbool)
True
>>>

df["column"][i + period]

大概可以写成

df.loc[i+period,"column"]

如果可以的话应该是。 索引的不同选择


为防止出现很长的 while 语句,可以在循环之前和底部将术语分配给名称。

a = df.loc[i+period,"column"]>min(df["column"]
b = min(df["column"]
while (a>b and newbool) or (a<=b and not newbool)):
    # all the other stuff
    ...
    a = df.loc[i+period,"column"]
    b = min(df["column"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM