迭代器

##迭代器

In [24]: ci = collections.Co

collections.Container  collections.Counter    


In [24]: ci = collections.Counter('1112312312sdfsdf')


In [25]: ci

Out[25]: Counter({'1': 5, '2': 3, 'd': 2, 'f': 2, 's': 2, '3': 2})


In [26]: ci.elements()

Out[26]: <itertools.chain at 0x7f8fd4f1b590>


In [27]: c2 = ci.elements()


In [28]: c2.next()

Out[28]: 'd'

##类里必须有__iter__

内部实现:内部实现有没有下一个


##生成器

基于yield生成


In [54]: range(10)

Out[54]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


In [55]: xrange(10)

Out[55]: xrange(10)

应用:

In [58]: listOne = [1,2,31,4,32]


In [59]: for i in range(len(list))

list     listOne  


In [59]: for i in range(len(listOne)):

   ....:     print lis

list     listOne  

   ....:     print listOne[i]

   ....:     

1

2

31

4

32


你可能感兴趣的:(python)