[英]x (> if bool else <) y
I'm looking for a logic to use a function with different operators.我正在寻找将 function 与不同运算符一起使用的逻辑。
Is there a way to implement the logic to use a boolean to determine the operator in the comparison?有没有办法实现使用 boolean 来确定比较中的运算符的逻辑? something along the lines of
类似的东西
while df["column"][i + period] (> if bool_var else <=) min(df["column"])
Edit: can anyone explicitly show me how that logic would be implemented with the operator module?编辑:任何人都可以明确地告诉我如何使用 operator 模块实现该逻辑吗?
while operator.gt(a, b) if bool_var else operator.eq(a, b): ?
To avoid duplicated blocks in your if/else
branching all you need is to change your while
statement basing on positive
flag and comparison operator created by operator module:为了避免
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
Another way would be to make two separate comparisons, each contingent on newbool
.另一种方法是进行两个单独的比较,每个比较都取决于
newbool
。 In this example a
is df["column"][i + period]
and b
is min(df["column"]
.在此示例中
a
是df["column"][i + period]
, b
是min(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]
Can probably be written as大概可以写成
df.loc[i+period,"column"]
If it can it should be.如果可以的话应该是。 Different choices for indexing .
索引的不同选择。
To prevent a very long while statement the terms could be assigned to names before and at the bottom of the loop.为防止出现很长的 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.