List generation, generators, iterators

Source: Internet
Author: User
Tags iterable

A word concept

List Generation--can be calculated directly in the list

Generator-the mechanism by which loops are computed, called Generators: Generator (that is, generating a function or list that is not running, that is, data flow)

The second sentence: the difference between generator and list-generator you do not know the length, is a data stream; list, dict, str you know the length

Iterators-objects that can be called by the next () function and constantly return the next value are called iterators

The second sentence: An iterative object-an object that can act directly on a for loop is called an iterative object: iterable

The third sentence: The generator must be an iterator, the iterator is not necessarily the generator

List-Generated
data = [1,2,2,34for in  data]     # Direct Operation  if  else for in data]     # ternary operation print(data)

Generator
First method, list push-to-type
 for  in range)       # use parentheses to indicate print# at this point only the function memory is printed,
The second complex approach
#斐波那契数列def FOB (num): a    b = 0,1    count = 0 while    count < num:        count + = 1        tmp = b     #也可以写成a, B=b, A+b        B = A + b        a = tmp        yield a     #返回a, while suspending the current function, a returns to the person who called the current function through __next__ ()        # return a    else:p Rint ("Done") F = FOB (1000000) for I in range:    print (f.__next__ ())

  

Iterators
>>> from Collections Import iterator>>> isinstance ((x to X in range), Iterator) true>>> are Instance ([], Iterator) false>>> isinstance ({}, Iterator) false>>> isinstance (' abc ', Iterator) False

  

Although the #list, Dict and Str are iterable, they are not iterator. Through the ITER () function, you can change the list, Dict, str and other iterable into Iterator using >>> isinstance (ITER ([]), Iterator) true>>> Isinstance (ITER (' abc '), Iterator) True

  




List generation, generators, iterators

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.