使用列表推导对数字加倍,直到达到x

时间:2019-01-12 20:41:57

标签: python python-3.x while-loop list-comprehension

我产生了下面的代码,可以正常工作。但是,我想找到一种使用列表推导或Lambda编写代码的更加Pythonic的方法。

n = 84

trillion = [n * 2, n *= 2 while n <= 1000000000000]

OR

lambda n: n*=2 while n <= 1000000000000

number = 84
while number <= 1000000000000:  
    print (number * 2) 
    number *= 2


168
336
772

1 个答案:

答案 0 :(得分:2)

我不确定在不涉及列表的情况下为什么要理解列表。但是,您可以简单地使用对数来计算最终结果。我还建议您使用10 ** 121_000_000_000_000而不是1000000000000使其更具可读性:

import math

number = 84

number *= 2 ** int(math.log2(10 ** 12 / number))

print(number)

721554505728