---restore content starts---
List Builder
for in range ()print(a)# Results [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
Above is a list builder
Insufficient: Not applicable for more data because it takes up too much memory
Generator
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.
So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop is calculated as a mechanism, called the generator: generator
Two ways to create generator:
- Change [] to ()
- Yield
for in range (+)print(a)#<generator Object <genexpr> at 0x0000000000a777d8> A is a generator object print(Next (a)) #对a进行访问 print(Next (a) ) Print (Next (a)) Print (Next (a))
#结果 1 2 3 4
For I in a: #a为生成器对象是可迭代的
Print (i)
# Results 5 6 7 8 9
defBar ():Print('Ok1') Count=yield1Print(count)Print('Ok2') yield2Print('OK3') yield3F=Bar () f.send (None)#equivalent to next (f)F.send ('eeee')#changing a variable in front of yield must first be f.send (None) to find the variable
Iterators
for
There 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
.
You can use to isinstance()
determine whether an object is an Iterable
object:
fromCollectionsImportiterabledefBar ():Print('Ok1') Count=yield1Print(count)Print('Ok2') yield2Print('OK3') yield3F=Bar ()Print(Isinstance (f,iterable))#true is the corresponding data type and vice versa
Summary:
Any object that can be used for for
the loop is a Iterable
type;
All objects that can be used for next()
functions are Iterator
types, which represent a sequence of lazy computations;
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
.
from Import = [1,2,4= iter (l)print(type (l))print( Isinstance (l,iterator))print(isinstance (l,iterable))print(Isinstance (L, List))
List Builder & Builder & Iterator