python3 迭代器

'''
总结:
Iterable: 可迭代对象,有__iter__()方法
Iterator: 迭代器,有__iter__()和__next__()方法
迭代器的特点:
1.节省内存。
2.惰性机制。
3.不能反复,只能向下执行。
'''
str1 = "hello"
for s in str1:
print(s)
'''
h
e
l
l
o
'''
int1 = 123
for i in int1:
print(i) # TypeError: 'int' object is not iterable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-8c7f77a7214a> in <module>()
1 int1 = 123
----> 2 for i in int1:
3 print(i) TypeError: 'int' object is not iterable
'''dir函数'''
dir(list)
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
print("__iter__" in dir(int))  # False
print("__iter__" in dir(bool)) # False
print("__iter__" in dir(str)) # True
print("__iter__" in dir(list)) # True
print("__iter__" in dir(set)) # True
print("__iter__" in dir(tuple)) # True
print("__iter__" in dir(dict)) # True
'''isinstance()函数可以查看一个对象是什么类型
iterable 迭代对象
iterator 迭代器
'''
lst = ["apple", "banana", "orange"]
lst_iter = lst.__iter__() # 迭代对象.__iter__()会生成一个迭代器
from collections import Iterable, Iterator
print(isinstance(lst, Iterable)) # True
print(isinstance(lst_iter, Iterable)) # True
print(isinstance(lst, Iterator)) # False
print(isinstance(lst_iter, Iterator)) # True
str1 = "hello"
str_iter = str1.__iter__()
print(str_iter.__next__()) # 迭代器有next方法,如果拿完数据,再执行next会报StopIteration,返回结果:h
print(str1.__next__()) # 迭代对象没有next方法
h
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-56c2a1c77dc2> in <module>()
2 str_iter = str1.__iter__()
3 print(str_iter.__next__())
----> 4 print(str1.__next__()) AttributeError: 'str' object has no attribute '__next__'
'''for循环机制'''
for i in [1, 2, 3]:
print(i)
1
2
3
'''使用while循环+迭代器来模拟for循环'''
lst = [1, 2, 3]
lst_iter = lst.__iter__()
while 1:
try:
print(lst_iter.__next__())
except StopIteration:
break
1
2
3
'''list可以一次性把迭代器中的内容拿空,并装载在一个新列表中'''
str1 = "hello".__iter__()
print(list(str1)) # ['h', 'e', 'l', 'l', 'o']
上一篇:jsp内置对象之request对象


下一篇:elasticsearch 基础 —— Delete By Query API