Skip to main content
 首页 » 编程设计

python之带步骤的循环

2025年05月04日19qq78292959

我创建了一个 python 脚本,它可以根据指定的步进函数循环遍历一系列值。

#!/usr/bin/python 
 
def mul(value, step): return value * step 
def inc(value, step): return value + step 
def step_range(start, end, step, func): 
    while start <= end: 
        yield start 
        start = func(start, step) 
 
def main(): 
    for x in step_range(1, 64, 2, mul):  
        print '%d, '%(x), 
    print 
    for x in step_range(0, 64, 8, inc):  
        print '%d, '%(x), 
 
if __name__ == '__main__': 
    main() 

输出:

$ python test.py 
1,  2,  4,  8,  16,  32,  64, 
0,  8,  16,  24,  32,  40,  48,  56,  64, 

有什么办法可以去掉辅助函数,让用户可以做这样的事情吗?

for x in step_range(1, 64, *2):  
    ... 
 
def step_range(start, end, step): 
    while start <= end: 
        yield start 
        start = start ?step? 

? 标记了我被难住的地方...我查看了 operator模块,但我必须知道 mul(a, b) 和 add(a, b) 函数的两个参数。

请您参考如下方法:

一个更清晰的方法可能是

def step_range(start, end, func): 
    while start <= end: 
        yield start 
        start = func(start) 

然后例如,你可以做

[a for a in step_range(1, 10, lambda x: x * 2)] # [1, 2, 4, 8] 

这样你就不会仅限于乘法或加法。当您阅读它时,它也更加 Pythonic 和清晰。