Iterator and generator 181030

Source: Internet
Author: User
Tags iterable
I. List Production
[ i*2 for i in range(10) ]
Ii. Generator)

The difference between a generator and a list is that the generator data is generated during the call and cannot be sliced like a list.

  • Data is generated only when called.
  • Only record the current location
  • Only one"Next"Method

    1. Generator 1
>>> (  i*2 for i in range(10)  )>>> for i in b:...     print(i)
2. Next method of Generator
>>> c = (  i*2 for i in range(10)  )>>> c.__next__()0>>> c.__next__()2>>> c.__next__()4
3. Fibonacci Series
# Author:Li Dongfeidef fib(max):    n, a, b = 0, 0, 1    while n < max:        print(b)        a, b = b, a + b        n = n + 1    return "done"fib(100)
4. Change Fibonacci to a generator.
# Author:Li Dongfeidef fib(max):    n, a, b = 0, 0, 1    while n < max:        yield b        a, b = b, a + b        n = n + 1    return "done"f = fib(100)print(f.__next__())print(f.__next__())print(f.__next__())print(f.__next__())print(f.__next__())
5. Capture exceptions
# Author:Li Dongfeidef fib(max):    n, a, b = 0, 0, 1    while n < max:        yield b        a, b = b, a + b        n = n + 1    return "done"f = fib(10)while True:    try:        x = next(f)        print('f:', x)    except StopIteration as e:        print('Generator return value:', e.value)        break
6. Generator parallelism (producer consumer model)
# Author: Li dongfeiimport timedef consumer (name): # Consumer While true: baozi = yield print ("steamed stuffed bun [% s], it was eaten by [% s! "% (Baozi, name) def producer (name): # producer c = Consumer (name) C. _ next _ () For I in range (10): time. sleep (1) print ("made 1 steamed stuffed bun! ") C. Send (I) # Sending I to consumer will be accepted by yield and assigned to baoziproducer (" dongfei ")
Iii. iterator)
  • Objects that can directly act on the for loop are collectively referred to as iteration objects: iterable
  • The object that can be called by the next () function and continuously return the next value is called the iterator: iterator

    1. determine whether an object can be iterated
>>> from collections import Iterable>>> isinstance([],Iterable)True>>> isinstance((),Iterable)True>>> isinstance('abc',Iterable)True
2. Determine whether it is an iterator object.
>>> from collections import Iterator>>> isinstance(  ( x for x in range(5) ), Iterator  )True

The generator must be an iterator, but not necessarily a generator.

3. Use the ITER () function to convert iterable, such as list, dict, and STR into iterator.
>>> a = [1, 2, 3]>>> b = iter(a)>>> b.__next__()1>>> b.__next__()2>>> b.__next__()3

Iterator and generator 181030

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.