提问人:PetersServers 提问时间:12/30/2022 最后编辑:PetersServers 更新时间:12/30/2022 访问量:80
x (> if bool else <) y
x (> if bool else <) y
问:
我正在寻找一种逻辑来使用具有不同运算符的函数。
有没有办法实现使用布尔值来确定比较中的运算符的逻辑?类似的东西
while df["column"][i + period] (> if bool_var else <=) min(df["column"])
编辑:任何人都可以明确地告诉我如何使用运算符模块实现该逻辑吗?
while operator.gt(a, b) if bool_var else operator.eq(a, b): ?
答:
1赞
RomanPerekhrest
12/30/2022
#1
为了避免分支中的重复块,您只需要根据运算符模块创建的标志和比较运算符来更改语句:if/else
while
positive
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
评论
0赞
PetersServers
12/30/2022
谢谢。解决了问题
1赞
RomanPerekhrest
12/30/2022
@PetersServers,不客气。实际上,您最初带有扩展代码的问题描述对我来说似乎很清楚(我不会从描述中删除该函数)。
1赞
wwii
12/30/2022
#2
另一种方法是进行两个单独的比较,每个比较都取决于 。在此示例中为 和 是 。newbool
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]
大概可以写成
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"])
评论
operator