If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:如果你需要迭代一個數字序列,內置函數Range()就方便了。它產生算術級數序列:
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the 『step』):給定的終點永遠不是生成序列的一部分;範圍(10)生成10個值,長度為10的序列的項目的合法索引。可以讓範圍從另一個數開始,或者指定一個不同的增量(甚至是負的;有時這被稱為「步驟」):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
To iterate over the indices of a sequence, you can combine range() and len() as follows:若要遍歷序列的索引,可以將range()和len()組合如下:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques.然而,在大多數這樣的情況下,使用numberate()函數是方便的,參見循環技術。
A strange thing happens if you just print a range:如果你只列印一個範圍,就會發生奇怪的事情:
>>> print(range(10))
range(0, 10) #要達到預期,可以用變量如for i in range(10):print(i)
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.多數情況,Range-()返回的對象的行為好像是一個列表,但實際上不是。返回的是一個對象,它在迭代時返回所需序列的連續項,但它並沒有真正列出列表,從而節省了空間。
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:這樣的對象是可迭代的,也就是說,它適合於函數和構造的目標,這些函數和結構期望它們能夠獲得連續的項直到耗盡。我們已經看到for語句是一個迭代器。函數List()是另一個;它從迭代中創建列表:
>>> list(range(5))
[0, 1, 2, 3, 4]