Python basis _ generators and iterators

The definition list

方法一:
a = [1,2,3,4,5,6,7,8,9] 
print(a)
方法二:
a = [x for x in range(10)]

如果要将列表中的数都乘以2:

方法一:
a = []
for i in range(10):
    a.append(i*2)
方法二:
a = [x*2 for x in range(10)]

As can be seen, the two definitions list number in the list changes, a second method is simpler than the method, the second method is called the list formula

Builder

Element of the list may be calculated out according to a certain algorithm, and when the execution of the loop continues to calculate the subsequent element, without having to implement a complete list generated, while the cycle, while calculation, this mechanism is called generator (generator).

Why use a generator?

If you create a list containing 10 million elements, is bound to account for a large memory space, and only need the first few elements will cause a waste of space, using generators dynamically generated elements can save a lot of memory.

Create a builder

//列表生成式
a = [i*2 for i in range(10)]  #[0,2,4,6,8,10,12,14,16,18]
//生成器
a = (i*2 for i in range(10))  #generator object <genexpr> at 0x0000017E4C38A6D8>

And generating a list of formula surface differences:

1. The list is defined by the formula [], defined by the generator ().

2. The result is a listing of formula list generation concrete elements, result generator for generator object <genexpr> at 0x0000017E4C38A6D8>.

Generator and the print result will need to use __ __ Next () method

a = (i*2 for i in range(10))
print(a.__next__())    #0
print(a.__next__())    #2
print(a.__next__())    #4
print(a.__next__())    #6
print(a.__next__())    #8
当元素输出完毕后会报错:print(a.__next__())    StopIteration

利用for循环输出:
a = (i*2 for i in range(10))
for i in a:
    print(i)

Defined by the function generator

//用函数实现输出累加的过程
def sum(num):
    a,sum = 0,0
    while num >= a:
        sum = sum + a
        a = a + 1
        print(sum)
    return "done"
sum(10)

//用生成器实现输出累加的过程
def sum(num):
    a,sum = 0,0
    while num >= a:
        sum = sum + a
        a = a + 1
        yield sum
    return "done"
print(sum(10))
结果:<generator object sum at 0x000001B3ED38B408>
f = sum(10)
print(f.__next__())
print(f.__next__())
结果:0 1

When the print (sum) to yield SUM, the accumulation function has become a generator, the function returns a value return is encountered, encountered when the generator executes the yield will return to the __next __ () at, when calling __next __ () method again, it will return to yield at the last exit to continue.

Generator send () method

def test():
    print("开始")
    while True:
        value = yield
        print("这是一个%s"%value)

f = test()
f.__next__()
f.send("生成器")
结果:开始
······这是一个生成器

send () is a very important generator method, can pass parameters to send using the method of the internal generator, the above example "generator" to the value

Why in the f = test (after) first add that f .__ next __ ()?

When executing the statement f = test (), the generator does not continue down, it will remain in def test (), only calls f .__ next __ (after) will continue down, looking for yield, yield found after the stop, the example outputs a start on a good description of the problem.

Iterables

Type can be directly used for the iterative loop may be referred to an object, for example: a list of tuples dictionary generator

Determine whether an object is iterable:

from collections import Iterable
isinstance([],Iterable)

Iterator

May be next () function call and continue to return value to become the next target iterator: Iterator

Determine whether an object is an iterator:

from collections import Iterator
isinstance((x for x in range(10)), Iterator)

 Note: iteration object that is not necessarily the iterator

List , 字典, tuples like Iterable(迭代对象)becomes Iterator(迭代器)possible to use iter()the function:

isinstance(iter([]), Iterator)

 

Guess you like

Origin blog.csdn.net/w819104246/article/details/92631296