Python-迭代器

>>> L = [1,2,3]

>>> for X in L:                # Automatic iteration

...    print(X ** 2, end=' ')        # Obtains iter, calls __next__, catches exceptions

...

1 4 9

>>> I = iter(L)                # Manual iteration: what for loops usually do

>>> while Ture:

...    try:                 # try statement catches exceptions

...      X = next(I)           # Or call I.__next()__

...    except StopIteration:

...      break

...    print(X ** 2, end=' ')

...

1 4 9

=======================================================

 enumerate(),用于获取index与对应位置的元素

>>> E = enumerate('spam')

>>> E

<enumerate object at 0x0382104F>

>>> I = iter(E)

>>> next(E)

(0,'s')

>>> next(E)

(1,'p')

>>> list(enumerate('spam'))

[(0,'s'),(1,'p'),(2,'a'),(3,'m')]

===================================================

原文地址:https://www.cnblogs.com/yy-is-ing/p/3954661.html