Python3 from zero--{initial consciousness: 004~ iterators and generators}

Source: Internet
Author: User

One, reverse iteration: Reversed ()

>>> a[1, 2, 3, 4] for in  reversed (a): ... Print (x, end="

#反向迭代只有在待处理的对象具有确定的大小或者对象实现了__reversed () __ Special methods to work, otherwise you must first convert the object to a list (may consume a lot of memory)

 >>> with open ( " /etc/passwd  , "   RT   " ) as file: ...  for  x #   ... print   (x) ... Traceback (most recent): File    , Line 2, in  < Module>typeerror:argument to reversed () must is a sequence  

Second, iterator slicing: itertools.islice

Import Itertools def count (n): ...    while True:    ... yield N. ...    n + = 1
... for in Itertools.islice (count (0), 2, ten): #相当于列表切片取 [2:10] ... Print (x, end="
 >>>for  x in  Itertools.islice (count (0), 5 print  (x, End= "  ) ...  if  x >10: ...  break   ...  5 6 7 8 9 10>>> for  x in  Itertools.islice (count (0), 5 print  (x, End= "  ) ...  0 1 2 3 4 

#迭代器和生成器无法进行普通的切片操作 (whose length is indeterminate and does not implement an index), Islice produces a new iterator that consumes all the data from the initial iteration sequence

Iii. iterative sequence in the form of index-value pairs: Enumerate

>>> a[1, 2, 3, 4] for in Enumerate (a, 1):    # starting from 1 counts, Syntax: Enumerate (iterable[, start])   ... Print  1 12 23) 34 4

#enumerate的返回值是一个迭代器, the element is a tuple

Iv. simultaneous iteration of multiple sequences

Parallel paired iterations: Zip (), itertools.zip_longest ()

>>>a[1, 2, 3, 4]>>>b[1, 2, 3, 4, 8, 9]>>> forX, yinchZip (A, b): ...Print(x, y) ...1 4>>> forX, yinchItertools.zip_longest (A, B): ...Print(x, y) ...1 12 23) 34 4None8None9>>> forX, yinchItertools.zip_longest (A, B, fillvalue=0): ...Print(x, y) ...1 12 23) 34 40809

Serial Sequential iterations: Itertools.chain ()

 for inch Itertools.chain (A, B): ...   Print  1234123489

Serial Cross Iteration: Heapq.merge ()

Import HEAPQ  for inch Heapq.merge (A, B): ...   Print  1122334489

Python3 from zero--{initial consciousness: 004~ iterators and generators}

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.