迭代器

#迭代器

迭代的工具,迭代是更新換代,也能夠說成重複,能夠基於上一次的結果推出下一次的結果python

可迭代對象

python中一切皆對象,對這一切的對象中 但凡是有__iter__方法的對象,都是可迭代對象。函數

x = 1  # 不可迭代對象

s = 'nick'  # 可迭代對象
s.__iter__()
lt = [1, 2, 3]  # 可迭代對象
dic = {'a': 1, 'b': 2}  # 可迭代對象
tup = (1,)  # 元組只有一個元素必須得加逗號# 可迭代對象
set = {1, 2, 3}  # 可迭代對象
f = open('time.py')  # 可迭代對象


def func():  # 不可迭代對象
    pass

Python內置str、list、tuple、dict、set、file都是可迭代對象.而後出了數字類型和函數以外都是可迭代對象工具

迭代器對象

具備__iter__以及__next__方法的叫作迭代器對象code

s = 'nick'  # 可迭代對象,不屬於迭代器對象
s.__iter__()
lt = [1, 2, 3]  # 可迭代對象,不屬於迭代器對象
dic = {'a': 1, 'b': 2}  # 可迭代對象,不屬於迭代器對象
tup = (1,)  # 元組只有一個元素必須得加逗號# 可迭代對象,不屬於迭代器對象
se = {1, 2, 3}  # 可迭代對象,不屬於迭代器對象
f = open('time.py')  # 可迭代對象,迭代器對象

只有文件是迭代器對象對象

# 不依賴索引的數據類型迭代取值
dic = {'a': 1, 'b': 2, 'c': 3}
iter_dic = dic.__iter__()
print(iter_dic.__next__())
print(iter_dic.__next__())
print(iter_dic.__next__())
# print(iter_dic.__next__())  # StopIteration:

a索引

bit

cio

# 依賴索引的數據類型迭代取值
lis = [1, 2, 3]
iter_lis = lis.__iter__()
print(iter_lis.__next__())
print(iter_lis.__next__())
print(iter_lis.__next__())
# print(iter_lis.__next__())  # StopIteration:
1

1for循環

2class

3

上面方法十分繁瑣,咱們能夠使用while循環精簡下。其中使用的try...except...爲異常處理模塊.

s = 'hello'
iter_s = s.__iter__()

while True:
    try:
        print(iter_s.__next__())
    except StopIteration:
        break

h
e
l
l
o

總結

可迭代對象: 具備__iter__方法的對象就是可迭代對象,除了數字類型和函數都是可迭代對象

迭代器對象: 具備__iter____next__方法的都是迭代器對象,只有文件

迭代器對象必定是可迭代對象; 可迭代對象不必定是迭代器對象

for循環原理

for循環==迭代器循環

dic ={'a':1,'b':2}
for i in dic:
    print(i)

# 1. 把lt(可迭代對象/迭代器對象)用__iter__方法轉換成迭代器對象
# 2. 使用__next__取出迭代器裏的全部值
# 3. 使用__next__方法取盡迭代器中的全部值,必定會報錯,經過異常捕捉退出while循環

# 解決了不依賴索引取值


# dic ={'a':1,'b':2}
# dic_iter = iter(dic)
# print(next(dic_iter))
# print(next(dic_iter))
相關文章
相關標籤/搜索