作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想写一个 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/
我是一名优秀的程序员,十分优秀!