查看 Python 中的非常大的数字 (1.2e+34)
look through a very large numbers (1.2e+34) in Python
已经在此处查看了 Google 和过去的问题,但找不到简单且解释清楚的答案。
如何循环遍历python中的大数?
例如我想检查在 1 和 1.2e+34 之间循环并打印最终结果需要多长时间。
不确定如何为此编写 look/while 循环,我不知道如何用 python 语言编写 1.2e+34 (For i = 1 to i = ?).
Python 将 1.2e34
理解为浮点数,但您可以将其转换为整数。 int(1.2e34)
.
如果你想在 1 和 n
之间循环,你通常会使用 range(1, n+1)
.
因此,在 Python 3:
for i in range(1, int(1.2e34)+1):
print(i) # or do whatever you want
--
正如 FHTMitchell 指出的那样,在 Python 2 中,该值对于 range
或 xrange
来说太大了。您可以改用 while
循环。
i = 1
while i <= 1.2e34:
print i # or do whatever you want
i += 1
也许你可以尝试这样的事情:
i = 1L
while True:
i += 1
if i == int(1.2e34):
print(i)
break
好的,所以你已经有了关于如何的答案,但你真的需要考虑一下你是否应该做吧。在我的机器上,速度不慢,iPython (py 3.6) 中的这段代码:
def f(n):
for i in range(10 ** n):
pass
%timeit f(6)
生产
10 loops, best of 3: 20.4 ms per loop
因此,如果您想在 1
和 1.2e34
之间循环,则需要 1.2e34 / 0.0204 = 5.77e35 秒或大约 10^18 times the age of the universe。
我认为你不想那样做...
已经在此处查看了 Google 和过去的问题,但找不到简单且解释清楚的答案。
如何循环遍历python中的大数?
例如我想检查在 1 和 1.2e+34 之间循环并打印最终结果需要多长时间。
不确定如何为此编写 look/while 循环,我不知道如何用 python 语言编写 1.2e+34 (For i = 1 to i = ?).
Python 将 1.2e34
理解为浮点数,但您可以将其转换为整数。 int(1.2e34)
.
如果你想在 1 和 n
之间循环,你通常会使用 range(1, n+1)
.
因此,在 Python 3:
for i in range(1, int(1.2e34)+1):
print(i) # or do whatever you want
--
正如 FHTMitchell 指出的那样,在 Python 2 中,该值对于 range
或 xrange
来说太大了。您可以改用 while
循环。
i = 1
while i <= 1.2e34:
print i # or do whatever you want
i += 1
也许你可以尝试这样的事情:
i = 1L
while True:
i += 1
if i == int(1.2e34):
print(i)
break
好的,所以你已经有了关于如何的答案,但你真的需要考虑一下你是否应该做吧。在我的机器上,速度不慢,iPython (py 3.6) 中的这段代码:
def f(n):
for i in range(10 ** n):
pass
%timeit f(6)
生产
10 loops, best of 3: 20.4 ms per loop
因此,如果您想在 1
和 1.2e34
之间循环,则需要 1.2e34 / 0.0204 = 5.77e35 秒或大约 10^18 times the age of the universe。
我认为你不想那样做...