参考 python 中以前的计算?



我想知道是否有办法在同一语句中引用计算的前一部分。

例如:

(random.randint(1, 2) * 10) + ... ## Is there a way to refer to the random number 
## previously  calculated, which will go in
## the space of the ellipsis?

我知道这可以使用变量来完成,但理想情况下我正在寻找单行代码。

谢谢!

简单的答案是否定的,没有办法。

这就是我的意思:这就是函数的用途。(Ofc你可以说这也是变量的用途 - 但它是齐头并进的)。

import random
func = lambda x: x*10 + x  # function alt1 
def func(x):               # function alt2
return x*10 + x

并用以下命令调用它:

func(random.randint(1, 2)) # and this can now in turn be used inside formulas

例如,您现在可以执行以下操作:

def calculate_something(x):
return x*x
calculate_something(func(random.randint(1, 2)))

如果你有一个相当不可读的单行,只使用一次(random.randint(1, 2) * 10),你可以做这样的事情:

[x + y for x, y in [[(random.randint(1, 2) * 10)] * 2]][0]

显然,使用变量是首选方法。

最新更新