对于循环(新手) [英] For loops (novice)

查看:164
本文介绍了对于循环(新手)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始学习Python,for循环的概念对我来说还是有点困惑。我知道它通常遵循格式 for y ,其中 y 只是一些列表。
$ b $ for > for someArray ,



而for循环代表(i = 0; i <9; i (0,9,-2)


$ b可以表示为 $ b

假设不是一个常量增量,而是希望 i * = 2 ,甚至 i * = i 。这是可能的,还是我不得不使用while循环呢?正如你所说,循环的一个迭代遍历元素的 一个列表。这个列表可以包含任何你喜欢的东西,所以你可以事先构建一个包含每一步的列表。

A for 循环也可以遍历生成器,这是一小段代码,而不是实际的列表。在Python中, range()实际上是一个生成器(在Python 2.x中, range() xrange()是生成器。)



例如:

 $ 

$ b $ in doubler(1):
print i

上面的代表循环会打印

  1 
2
4
8

等等,直到您按下Ctrl + C。


I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format for x in y, where y is just some list.

The for-each loop for (int n: someArray) becomes for n in someArray,

And the for loop for (i = 0; i < 9; i-=2) can be represented by for i in range(0, 9, -2)

Suppose instead of a constant increment, I wanted i*=2, or even i*=i. Is this possible, or would I have to use a while loop instead?

解决方案

As you say, a for loop iterates through the elements of a list. The list can contain anything you like, so you can construct a list beforehand that contains each step.

A for loop can also iterate over a "generator", which is a small piece of code instead of an actual list. In Python, range() is actually a generator (in Python 2.x though, range() returned a list while xrange() was the generator).

For example:

def doubler(x):
    while True:
        yield x
        x *= 2

for i in doubler(1):
    print i

The above for loop will print

1
2
4
8

and so on, until you press Ctrl+C.

这篇关于对于循环(新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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