Beginner Python Essays-list Builder, generator, and iterator

Source: Internet
Author: User
Tags generator iterable

List Builder
# Common is the range () to create a list of numbers >>>[x*x for x in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# back can also be added with a judgment statement >>>[ X*x for x in range (ten) if x%2 = = 0][0, 4, 16, 36, 64]# characters can also play this way >>> [M + N for m in ' ABC ' for n ' XYZ ' [' AX ', ' A Y ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

  

Generator
# Generator is to replace the [] list generator (), or use the yield keyword in the function >>> L = [x * x for x in range]]>>> l[0, 1, 4, 9, 16, 25, 36, 49, 81]>>> g = (x * x for x in range) >>> G<generator object <genexpr> at 0x1022ef630># Value, you can use next (), but most use the for# Fibonacci sequence def fib (max):    n,a,b = 0,0,1 while    n < max:        #print (b)        yield  b A,        b = b,a+b        n + = 1    return ' done ' # use for loop to print to return the return value, you need to catch the stopiteration error, the return value is contained in the value of stopiteration:

  

forThere are several types of data that can be directly acting on a loop:

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

An object that can be called by next() a function and continually returns the next value is called an iterator: Iterator,它们表示一个惰性计算的序列 .

Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

You can use to isinstance() determine whether an object is an Iterable object

Beginner Python Essays-list Builder, generator, and iterator

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.