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:
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
.
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