Python-Review of Knowledge Points 2

List Compilation:

List Compilation:

  li=[x+1 for x in range(10)]

  List comprehension values:

  print (li)

Builder:

  g = (x+1 for x in range(10))

  1. What is a list generator:

    The mechanism that generates values ​​while computing in python is called a generator.

  2. List generator values:

    1. Take the value through the next() function - eg: next(g)

      1. The list generator can take values ​​through the next() function. If there is no value, a stopiteration exception will be thrown

    2. Take values ​​through a for loop.

      1. No error will be reported through the for loop

  3. Generators can also be implemented through functions

    1. Fibonacci function

def fib(max):
    n,a,b = 0,0,1
    while n<max:
     print(b) a,b
=b,a+b n+=1 return 'done' print(fib(10))

    2. Change print to yield to become a function generator

def fib(max):
    n,a,b = 0,0,1
    while n<max:
        yield b
        a,b=b,a+b
        n+=1
    return 'done'
name = fib(10)
print(name.__next__())

for i in fib(3):
    print(i)

    3. The generator with yield function generates values ​​through next(), and returns when yield is encountered.

iterator:

   1. There are two types of iterable objects:

      1. One is the data type that can pass through the for loop - including list, dict, set, tuple, str

      2. One is a generator, which takes values ​​through next() and a function generator with yield.

   2. You can directly convert the for loop into an iterable object: iterable.

   3. You can use isinstance() to determine whether an object is an iterable object.

   4. You can use the iter() function to convert an iterable object (list, dict, str) into an iterator.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324937320&siteId=291194637