Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
最具python风格的多次迭代方式_Python_Python 3.x - Fatal编程技术网

最具python风格的多次迭代方式

最具python风格的多次迭代方式,python,python-3.x,Python,Python 3.x,我回顾了一些算法,它们有一个for循环,增加了一个常数倍。解决这一问题的最佳方法是什么 这不是一个如何解决问题的问题,而是一个关于最佳解决方案的讨论 这是Java剪报: for (int i = 1; i <=n; i *= c) { // some stuff } 第一个帖子在这里。希望我的标签正确无误…您仍然可以这样做: def mrange(start, stop, step): i = start while i < stop: yi

我回顾了一些算法,它们有一个for循环,增加了一个常数倍。解决这一问题的最佳方法是什么

这不是一个如何解决问题的问题,而是一个关于最佳解决方案的讨论

这是Java剪报:

for (int i = 1; i <=n; i *= c) {
    // some stuff
}

第一个帖子在这里。希望我的标签正确无误…

您仍然可以这样做:

def mrange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i *= step
印刷品:

1
4
16
64
Python不能提供满足所有需求的默认范围函数,但创建自己的生成器是Python的风格


如果您不喜欢此解决方案,
while
替代方案看起来也不错。

您可以使用
itertools.accumulate
;从范围1到
n
开始,然后应用一个函数,该函数将其第一个参数乘以常数,并忽略其第二个参数

>>> from itertools import accumulate
>>> [x for x in accumulate(range(1,10), lambda x,_: 4*x)]
[1, 4, 16, 64, 256, 1024, 4096, 16384, 65536]
如果错过了要获取小于
n
的值,请从无限序列
[c,c**2,c**3,c**4,…]
开始,然后使用
takewhile
对其进行“过滤”。(此外,我刚刚意识到您只需要
map
,而不需要
acculate
,尽管
acculate
可能更有效。请注意使用
map
acculate
时起点的不同。)

>>来自itertools导入计数,takewhile
>>>n=100
>>>[x代表takewhile中的x(λx:x>>[x表示takewhile中的x(λx:x
使用数学模块:-

for i in range(math.ceil(math.log(limit, const))):
    # code goes here
例:-

类似于:

i = 1
while i< 20:
    print('runs')
    i*=2 

很可能是这样。我只是觉得存储一个计数值并手动更新它不是Pythonic…我不认为它是Pythonic,这是指数,是线性增量。这特别指的是没有“范围”替代方案(我知道)的多个情况。这就是我喜欢C/Php的地方(对于这种情况)@Adam_Karlstedt
range
只能提供一个算术序列。我还打算
accumulate
但循环不能超过上限
10
啊,误读了这个问题。我会更新
takewhile
count
@chepner,它会增长)我不确定这是目标是Pythonic,这似乎比原来的while循环更难阅读。。。
for i in range(math.ceil(math.log(limit, const))):
    # code goes here
>>> for i in range(math.ceil(math.log(20, 2))):
...     print("runs")
... 
runs
runs
runs
runs
runs
i = 1
while i< 20:
    print('runs')
    i*=2 
>>> import math
>>> mrange = lambda i, limit, const: range(i, math.ceil(math.log(limit, const)))
>>> for i in mrange(0, 20, 2):
        print('whoa')
.. 
whoa
whoa
whoa
whoa
whoa