请参阅python中的先前计算?

时间:2018-02-18 14:24:17

标签: python python-3.x

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

例如:

(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?

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

谢谢!

2 个答案:

答案 0 :(得分:1)

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

这就是我的意思:这就是函数的用途。 (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)))

答案 1 :(得分:0)

如果你只使用(random.randint(1, 2) * 10)一次,而且不可读的单行,你可以这样做:

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

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