[英]I'm trying to figure out how increment for loop in powers of 2
I'm used to code in C and i'm currently stuck on a for loop in python.我习惯于在 C 中编码,我目前被困在 python 中的 for 循环中。
In C the for loop looks something like for(int i, i<=1024,i*=2){}
.在 C 中,for 循环类似于for(int i, i<=1024,i*=2){}
。
I've tried for i in range(1,1024,*2)
,but it seems it doesn't accept *我试过for i in range(1,1024,*2)
,但它似乎不接受 *
i'm currently using我目前正在使用
Distance = 1
increment = 2
SearchRange = 1024
while Distance<SearchRange:
Distance *=increment
to achieve similar results, is there anything i can do in one line in python to make it work.为了达到类似的结果,我可以在 python 的一行中做些什么来使其工作。
I'm sure I'm missing something very simple.Please help!Thanks!我确定我错过了一些非常简单的东西。请帮忙!谢谢!
To do it using while loops:使用 while 循环来做到这一点:
step = 1
i = 1
while i <= 1024:
print(i)
i *=2
Output: Output:
1
2
4
8
16
32
64
128
256
512
1024
In Python, it would be written:在 Python 中,它会写成:
for i in range(1024):
i*=2
Check out https://wiki.python.org/moin/ForLoop for lots of other examples.查看https://wiki.python.org/moin/ForLoop了解更多其他示例。
This should work just fine:这应该可以正常工作:
>>> for i in range(15) :
... print 1 << i,
...
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384
>>>
A new answer since the question was updated:自问题更新以来的新答案:
iterable_range = [ 2**j for j in range(0,1024) ]
for i in iterable_range:
print(i)
Using a for loop you supply an iterable
from which the value is selected each iteration.使用 for 循环,您可以提供一个iterable
,每次迭代都从中选择值。 Its not like C where index i
is modified.它不像修改索引i
的 C。 So, to achieve the same in Python, you need to create an iterable of all the values.因此,要在 Python 中实现相同的效果,您需要创建一个包含所有值的可迭代对象。
This produces the desired:这会产生所需的:
1
2
4
8
16
32
64
128
etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.