[英]Python Compact function into String
I have a function like so:我有一个 function 像这样:
def ease_bounce_out(t, bounces=None):
if bounces is None:
bounces = [4 / 11, 6 / 11, 8 / 11, 3 / 4, 9 / 11, 10 / 11, 15 / 16, 21 / 22, 63 / 64]
bounces.insert(0, 1 / bounces[0] / bounces[0])
if t < bounces[1]:
return bounces[0] * t * t
else:
for i in range(3, len(bounces) - 2, 3):
if t < bounces[i]:
t -= bounces[i - 1]
return bounces[0] * t * t + bounces[i + 1]
t -= bounces[len(bounces) - 2]
return bounces[0] * t * t + bounces[len(bounces) - 1]
and I would like to compact it all down into 1 string so that I can use the eval()
function to get an output for any value of t
.我想把它全部压缩成一个字符串,这样我就可以使用
eval()
function 来获得 output 的任何值t
。 I have an example of an easier function:我有一个更简单的 function 示例:
def ease_poly(t, power=2):
t *= 2
if t < 1:
return t ** power
else:
return 2 - ((2 - t) ** power)
would become:会成为:
def ease_poly(power=2):
return f"(t * 2) ** {power} if (t * 2) < 1 else 2 - ((2 - (t * 2)) ** {power})"
This way, I could use this string and evaluate the function for any value of t
by simply doing:这样,我可以使用此字符串并通过简单地执行以下操作来评估 function 的任何
t
值:
ease = ease_poly(power=3)
t = 0.4 # 0 <= t <= 1
print(eval(ease))
Now to get started with my question, it doesn't actually have to be 1 line, this is what I've been thinking of:现在开始我的问题,它实际上不必是 1 行,这就是我一直在想的:
def ease_bounce_out(bounces=None):
if bounces is None:
bounces = [4 / 11, 6 / 11, 8 / 11, 3 / 4, 9 / 11, 10 / 11, 15 / 16, 21 / 22, 63 / 64]
return # some code here that compiles the rest into a string
A small tip,一个小提示,
bounces[ -1 ] = Last item反弹[ -1 ] = 最后一项
bounces[ -2 ] = Last second item反弹[ -2 ] = 最后第二项
Don't use bounces[ len(bounces) - 1 ]不要使用反弹[ len(bounces) - 1 ]
Answer: You can't have that string answer with eval.答案:你不能用 eval 得到那个字符串答案。 Because your function is making decisions based on t .
因为您的 function 正在根据 t 做出决定。 You have to pass t.
你必须通过 t。
If evaluating for all t is your primary concern then other way could help.如果评估所有 t 是您的主要关注点,那么其他方式可能会有所帮助。 Forget about eval.
忘记评估。 Don't pass t but use t in function then it will look up in global scope and uses t in that scope.
不要传递 t 但在 function 中使用 t 然后它将在全局 scope 中查找并在 scope 中使用 t。
Example:例子:
This function requires t to be passed.这个 function 需要 t 才能通过。
def mathuer(t, b = 23 ):
x = t
if b > t:
x = t
return x
This function uses global t.此 function 使用全局 t。
def mathuer(b = 23 ):
x = t
if b > t:
x = t
return x
This is how it works,这就是它的工作原理,
t = 34
obj = mathuer() // Uses t defined above
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.