枚举与迭代
-
>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> list(enumerate(['Python','Java']))
[(0, 'Python'), (1, 'Java')]
>>> list(enumerate({'a':97,'b':98,'c':99}.items()))
[(0, ('a', 97)), (1, ('b', 98)), (2, ('c', 99))]
>>> for index,value in enumerate(range(10,15)):
... print((index,value),end=' ')
...
(0, 10) (1, 11) (2, 12) (3, 13) (4, 14) >>>
>>> for item in enumerate(range(5), 6): # 指定枚举时的索引起始值
... print(item,end=',')
...
(6, 0),(7, 1),(8, 2),(9, 3),(10, 4),>>> -
iter()函数用来返回指定对象的迭代器,有两种用法
-
iter(iterable)
要求参数必须为序列或者有自己的迭代器
-
iter(callable,sentinel)
持续调用参数callable直至其返回sentinel
-
-
next()函数用来返回可迭代对象中的下一个元素,适用于生成器对象以及zip、enumerate、reversed、map、filter、iter等对象,等价于这些对象的next()方法
>>> x = [1, 2, 3]
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
>>> y = iter(x) # 根据列表创建迭代对象
>>> next(y)
1
>>> next(y)
2
>>> next(y)
3
>>> next(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> x = range(1,100,3)
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'range' object is not an iterator
>>> y = iter(x)
>>> next(y)
1
>>>
>>> next(y)
4
>>> next(y)
7
>>> next(y)
10
>>> next(y)
13
>>> next(y)
16
>>> x = {1, 2, 3}
>>> y = iter(x)
>>> next(y)
1
>>> next(y)
2
>>> class T:
... def _ _init_ _(self,seq):
File "<stdin>", line 2
def _ _init_ _(self,seq): ^SyntaxError: invalid syntax>>> class T:... def __init__(self,seq):... self.__data=list(seq)... def __iter__(self):... return iter(self.__data)...>>> t = T(range(3))>>> next(t)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'T' object is not an iterator>>> ti = iter(t)>>> next(ti)0>>> next(ti)1>>> from queue import Queue >>> q = Queue() # 创建队列对象>>> for i in range(5):... q.put(i)...>>> q.put('END')>>> def test():... return q.get()...>>> for item in iter(test,'END'):... print(item,end=' ')...0 1 2 3 4 >>>>>> x = map(int,'1234') # map支持next()函数>>> next(x)1>>> next(x)2>>> x.__next__()3>>> x = reversed('12345678') # reversed支持next()函数>>> for i in range(4):... print(next(x),end=' ')...8 7 6 5 >>>>>> x = enumerate({'a':97, 'b':98, 'c':99}.items()) # enumerate支持next()函数>>> next(x)(0, ('a', 97))