程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

5、 Python learning notes - functions - iterators

編輯:Python
# iterator
"""
1、 Generators are iterators , Iterators don't have to be generators
2、 An iterator is one that satisfies the following conditions
Yes iter Method
Yes next Method
"""
# Example 1、 An iterator
list1 = [1, 2, 4]
d = iter(list1)
# Print type
print(type(d))
# Value
next(d)
next(d)
# for The essence of the cycle
"""
1、 Call the iter Method returns an iterator object
2、 Calling iterator's next Methods the values
3、 Handle stopIteration abnormal ( Get all the values in the iterator )
"""
# Determine if it's an iterator
from collections import Iterable, Iterator
print(isinstance(d, Iterator)) # Is it an iterator
print(isinstance(d, Iterable)) # Whether it can be iterated
# Summary
"""
1、 It is usually used for All of them are Iterable
2、 All have next The are Iterator
3、 The collection data type is as follows list,truple,dict,str, All are Itrable No Iterator, But it can go through iter() Function to get a Iterator object
"""
# Example 2Iterable and Iterator
# Tuple dictionaries are all iteratable
print(isinstance({}, Iterable))
print(isinstance((), Iterable))
print(isinstance(100, Iterable))
# Tuple dictionaries are not iterators , But it can go through iter(), Function to get an iterator
print(isinstance({}, Iterator))
print(isinstance((), Iterator))
print(isinstance((iter([])), Iterator))
# for The essence of the cycle 1, Call the iter Method returns an iterator object
print(isinstance((x for x in range(10)), Iterator))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved