gpt4 book ai didi

python - For 循环遍历 2 的幂

转载 作者:行者123 更新时间:2023-12-05 08:17:28 24 4
gpt4 key购买 nike

我想写一个 for 循环,它会为每个循环迭代 2 的幂。

例如我想要一个这样的范围:

2, 4, 8, 16, ... , 1024

我该怎么做?

最佳答案

您可以使用 generator expression以便它根据需要生成数字并且它们不会浪费内存:

>>> for x in (2**p for p in range(1, 11)):
... print(x)

2
4
8
16
32
64
128
256
512
1024

在 Python 2 中,您可以使用 xrange 而不是 range 来保持它作为生成器并避免创建不必要的列表。

如果你想输入实际停止点而不是功率停止点,这可能是最简单的方法:

from itertools import count
for x in (2**p for p in count(1)):
if x > 1024:
break
print(x)

您可以将所有内容放在一行中:

from itertools import count, takewhile
for x in takewhile(lambda x: x <= 1024, (2**p for p in count(1))):
print(x)

但这变得很愚蠢(而且可读性不强)。

关于python - For 循环遍历 2 的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31872713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com