如何在Python中转换这种类型的循环 [英] How to convert this type of for loop in python

查看:166
本文介绍了如何在Python中转换这种类型的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int N = 20; (i = 1; i   



<我会1,4,13

我只能用它来完成它

$ pre > ,而我< N:
i = 3 * i + 1

如何使用另一种风格在Python中?



对不起我的英文。

解决方案

从Python的角度来看,循环实现没有任何问题。如果你想要一个通用的循环结构来模拟C / C ++ / Java的循环结构,你可以做类似的事情。 ;> (i):
收益
i = incr(i)


>>>列表(循环(1,lambda e:e <20,lambda e:3 * e + 1))
[1,4,13]

一旦创建了循环例程,就可以使用它创建任何自定义的循环格式,如您所愿

<$ p $ (1,lambda e:e< 20,lambda e:3 * e + 1):
print i


for example this kind of for loop in JAVA or C++:

int N = 20;
for (i = 1; i < N; i = 3 * i + 1)

i will be 1, 4, 13

I can only use while to complete it

while i < N:
    i = 3 * i + 1

How can write it using another kind of style in python?

Sorry for my English.

解决方案

Your while loop implementation is nothing wrong from Python's perspective. If you want a generalized loop structure to mimic the loop structure of C/C++/Java you can do something similar

>>> def loop(init, cond, incr):
    i = init
    while cond(i):
        yield i
        i=incr(i)


>>> list(loop(1, lambda e:e < 20, lambda e:3*e + 1))
[1, 4, 13]

Once you create the loop routine, you can use it to create any custom loop format as you desire

for i in loop(1, lambda e:e < 20, lambda e:3*e + 1):
    print i

这篇关于如何在Python中转换这种类型的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆