2017-08-07 99 views
0

乘数我只是想弄清楚如何像这样(用C编写的)增加:for循环在Python - 迭代应通过100

for (long long i = 100; i <= pow(10,length); i = i * 100){} 

将被翻译成Python 3 作为最后一部分,迭代器应该将自身乘以100,就是我陷入困境的地步。

任何援助将不胜感激。

+0

你目前的尝试? –

+2

那么''for'循环本质上就是'while'循环... – ForceBru

回答

8

使用while环代替:

i = 100 
while i <= 10 ** length: 
    # .... 
    i *= 100 

,或者使用发电机功能:

def powerranger(start, end, mult): 
    val = start 
    while val <= end: 
     yield val 
     val *= mult 

for i in powerranger(100, 10 ** length, 100): 
    # ... 
+0

只是为了这个名字:) –

+0

发电机FTW! – Sagar

+0

@MadPhysicist:https://i.stack.imgur.com/BgCFB.jpg –

1

而不是使用一个for循环中,该C型环将使用while循环更好地翻译:

i = 100 
while i <= pow(10, length): 
    # Use the value of `i` here. 
    i *= 100 
-1
j = 100 
for i in range(length): 
    j *= 100 
    print j # or other use of j 

不太Python的,但它的工作原理。

+0

我乘以'10 ** 2',条件是原始问题中的<=',所以你可能想要更多的东西像'range(length // 2 + 1)' –

0

进口很多东西:

from itertools import takewhile, count 

for i in (100 ** x for x in takewhile(lambda y: y <= length // 2, count(1))): 
    # do something useful here