如何使用 for 循环在 python 中实现" for (int i=0; i<str.size; i= i*5) "?



我可以在这里使用range((吗,或者有其他方法吗

您只需使用while即可:

i = 0 // maybe 1 would be better?
while i < someSize:
doSomething()
i *= 5

请注意,如果像您在标题中所做的那样,从零开始,这是一个无限循环(当然,除非someSize为零(。如何多次将0乘以5并不重要,最终总是0。


顺便说一句,没有什么可以阻止您创建自己的迭代器,即使是调用函数来决定下一个值以及迭代器是否应该停止的迭代器。

以下代码提供了这样一个beast,其中指定初始值和一对函数来更新和检查值(在测试代码中实现为lambdas(:

# Iterator which uses a start value, function for calculating next value,
# and function for determining whether to continue, similar to standard
# C/C++ for loop (not C++ range-for, Python already does that).
class FuncIter(object):
def __init__(self, startVal, continueProc, changeProc):
# Store all relevant stuff.
self.currVal = startVal
self.continueProc = continueProc
self.changeProc = changeProc
def __iter__(self):
return self
def __next__(self):
# If allowed to continue, return current and prepare next.
if self.continueProc(self.currVal):
retVal = self.currVal
self.currVal = self.changeProc(self.currVal)
return retVal
# We're done, stop iterator.
raise StopIteration()
print([item for item in FuncIter(1, lambda x: x <= 200, lambda x: x * 4 - 1)])

表达式:

FuncIter(1, lambda x: x <= 200, lambda x: x * 4 - 1)

生成使用等效的C/C++for语句获得的值:

for (i = 1; i <= 200; i = i * 4 - 1)

如输出所示:

[1, 3, 11, 43, 171]

相关内容

最新更新