Python functions and common modules-iterators

Source: Internet
Author: User
Tags generator generator iterable stdin

Iterators

We already know that there are several types of numbers that can directly act on a For loop:

    • A type is a collection of types: list, tuple, dict, set, str, bytes, and so on.
    • The other category is generator, which includes generators and generator function with yield.

These can act directly on the for loop, which is called an iterative pair (iterable):

An iterative pair of images that can be thought of as accomplishment 可以循環的對象 ,可迭代 = 可循環

Can be used to isinstance() determine whether an image is Iterable 對象 :

#!/usr/bin/env python3# -*- coding:utf-8 -*-from collections import  Iterableprint("[] list 列表是否為可迭代對象:", isinstance([], Iterable))print("() tuple 元組是否為可迭代對象:", isinstance((), Iterable))print("{} dict 字典是否為可迭代對象:", isinstance({}, Iterable))print("( x for i in range(10) ) generator 生成器是否為可迭代對象:", isinstance( ( x for i in range(10) ), Iterable))print("123 數字是否為可迭代對象:", isinstance(123, Iterable))---------------執行結果---------------[] list 列表是否為可迭代對象: True() tuple 元組是否為可迭代對象: True{} dict 字典是否為可迭代對象: True( x for i in range(10)  generator 生成器是否為可迭代對象: True123 數字是否為可迭代對象: FalseProcess finished with exit code 0

The generator can not only act on the for loop, but can also be adjusted and returned to the __next__() next value, until the last Stopiteration is thrown, indicating that the next value will not continue to be returned.

Note that this is important as an 可以被 __next__() 函數調用,並不斷地返回下一個值的對象 iterator (Iterator)

Can be used to isinstance() judge whether an image isIterator 對象

#!/usr/bin/env python3# -*- coding:utf-8 -*-from collections import Iteratorprint("[] list 列表是否為迭代器:", isinstance([], Iterator))print("() tuple 元組是否為迭代器:", isinstance((), Iterator))print("{} dict 字典是否為迭代器:", isinstance({}, Iterator))print("( x for i in range(10) ) generator 生成器是否為迭代器:", isinstance( ( x for i in range(10) ), Iterator))print("123 數字是否為迭代器:", isinstance(123, Iterator))---------------執行結果---------------[] list 列表是否為迭代器: False() tuple 元組是否為迭代器: False{} dict 字典是否為迭代器: False( x for i in range(10) ) generator 生成器是否為迭代器: True123 數字是否為迭代器: FalseProcess finished with exit code 0

The generator is definitely an iterator, because there are __next__() methods 但迭代器一定是生成器嗎?答案是不一定 .

Generators are Iterator, but list, dict, and Str are iterable, but not Iterator.

If you want to change the list, Dict, str and other iterable into iterator, you can use the iter() function:

  #!/usr/bin/env python3#-*-coding:utf-8-*-from Collections Import Iteratorprint ("ITER ([]) list lists are iterators:", Isinstance (ITER ([]), Iterator)) print ("ITER (()) tuple tuples are iterators:", Isinstance (ITER (()), Iterator)) print ("Iter ({}) d Whether the ICT dictionary is an iterator: ", Isinstance (ITER ({}), Iterator)) print (" Iter ((x for I in range) "Generator generator is an iterator:", Isinstanc E (ITER ((x for I in range), Iterator)) print ("ITER (123) number is an iterator:", Isinstance (ITER (123), Iterator))----------- ----Results---------------iter ([]) list is an iterator: Trueiter (()) A tuple tuple is an iterator: Trueiter ({}) Dict dictionary is an iterator: Trueiter (( X for I in range) generator generator is an iterator: Truetraceback (most recent called last): File "/python/project/interator_prat ice.py ", line 123, in <module> print (" iter () numbers are iterators: ", Isinstance (ITER (123), Iterator)) TypeError: ' int ' obj ECT is not iterableprocess finished with exit code 1  

Create an ordinary list called a = [ 1, 2, 3, ] , then use iter(a) the function, and at this point it is an iterator, then in the gifted value b = iter(a) , and then to use the __next__() method to adjust it.

>>> from collections import Iterator>>> a = [ 1, 2, 3 ]>>> iter(a)<list_iterator object at 0x10f91ee80>>>> b = iter(a)>>> b.__next__()1>>> b.__next__()2>>> b.__next__()3>>> b.__next__()Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>

You might ask, why is the list, dict, str, and other types of numbers not Iterator?

This is because the Iterator of Python represents a stream, and the Iterator can be used by a function to return to __next__() the next number until it is not available, and StopIteration的錯誤 it can be viewed as a single stream 有序序列 , which is a But we can not know in advance the length of the sequence, can only be continuously through the __next__() function to calculate the next one, so the iterator is 惰性的 only when it is necessary to return to the next number, it will be calculated.

Iterator can even represent an infinite number of streams, such as the whole natural number. The use of lists is never possible to save whole natural numbers.

Small knot

    • 凡是可以作用於for循環的對象都是 Iterable 類型
    • 凡是可作用於 __next__() 函數的對象,都是 Iterator 類型,它們表示一個惰性計算的序列
    • 集合數據類型,如: list 、 dict 、 str 等是 Iterable ,但不是 Iterator ,不過可以通過 iter() 函數獲得一個 Iterator 對象。

Python's for-loop is essentially a matter of passing through the next() function, for example:

#!/usr/bin/env python3# -*- coding:utf-8 -*-for i in [1, 2, 3, 4, 5]:    print(i)

Actually, it's exactly the code below.

#!/usr/bin/env python3# -*- coding:utf-8 -*-# 先獲得 Iterator 對象it = iter([1, 2, 3, 4, 5])# 循環while True:    try:        # 獲取下一個值        x = next(it)                # 把取到的值給打印出來        print(x)        # 遇到 StopIteration 就退出循環    except StopIteration:        break

Through the interpretation of the above code, you can clearly understand that the Python 3.x range () function, which is itself an iterator, is just sealed up.

Python 3.6.0 (default, Dec 24 2016, 00:01:50)[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> range(0, 10)range(0, 10)>>>

But the range () function in Python 2.7 is just a list

Python 2.7.13 (default, Apr  4 2017, 08:46:44)[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> range(0, 10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>

In Python 2.7, you want to change the range () function to an iterator, and you can use the xrange () function as an iterator.

Python 2.7.13 (default, Apr  4 2017, 08:46:44)[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> xrange(0, 10)xrange(10)>>>

Is it really an iterator? To ... Let's experiment.

  Python 2.7.13 (default, APR 4, 08:46:44) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on Dar Wintype "Help", "copyright", "credits" or "license" for more information.>>> dir (xrange (0, ten)) [' __class__ ', ' __ Delattr__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __getitem__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __len__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __reversed__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __ subclasshook__ ']>>> i = xrange (0, ten) >>> a = iter (i) >>> dir (a) [' __class__ ', ' __delattr__ ', ' _ _doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __length_hint__ ', ' __new__ ', ' __reduce ' __ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' Next ']>>> A.next () 0 ... (abbreviated) >>> A.next () 9>>> a.next () Traceback (most recent call last): File "<stdin>", line 1, in <mod Ule>stopiteration  

OK, now everybody knows what is the 可迭代對象 heel 迭代器 , then next come to test everybody a question

a = [ 1, 2, 3 ]
    • Q1: Is the above code 可迭代對象 ?

Ans: Yes. The following is a detailed solution

>>> from collections import Iterable>>> a = [ 1, 2, 3 ]>>> print("a 是否為可迭代對象:", isinstance(a, Iterable) )a 是否為可迭代對象: True
    • Q2: Is the above code 迭代器 ?

Ans: No. Because a there is __next__ no method, so it is not called an iterator, we can find out how dir() a can be used in all of the following.

>>> dir(a)[‘__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‘]>>>

Python functions and common modules-iterators

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.