The difference between a list derivation and a generator in Python3:
(1)
The list derivation is to load all the values into memory at once
The builder converts a list-inferred [] to (), does not load all values into memory at once, delays the calculation, returns one result at a time, and it does not produce all the results at once, which is useful for processing large amounts of data.
Fun ():
Range (1,50): Sleep
(1)
i
Fun ():
print ( I
# generator Function: A function contains the yield key, then this function is not a normal function, is a generator function
# call the generator function, not immediately execute the code inside the function, but will return a generator
Func ():
print ("a")
yield
print ("B")
yield
Print ("C")
yield
Print ("D")
yield
Generator = func ()
print (generator)
print (Type (generator))
# Next (Generator)
# next (Generator)
# Next (Generator)
Generator: Pass
Range (10000000000))
Range (10000000000)])
The first one has almost no memory footprint, and the second memory occupies a lot
Principle: The built-in function in Python3 when the SUM function uses the iterator protocol to access the object, and the generator implements the iterator protocol, so we can directly compute the sum of a series of values without having to construct a list first.
The builder can also improve the readability of your code:
# for a paragraph of text, where
each word appears index_words (text): Result
= []
text:
result.append (0)
Enumerate (text,1): ": Result.append (
index)
Result
index_words (text):
text:
0
Enumerate (text,1):
':
Index
(2)
List derivations can traverse any of the Times
The builder can only traverse once
Range (1,5)) print
(next generator) print (
next (generator)
) Generator:
Print (i
)generator:
print (i)
Print results:
1
2
3
4
Range (1,5)]
print (list1[0])
print (list1[1])
print (list1[2)
list1:
print (i)
list1: Print (
i)
Print results:
1
2
3
1
2
3
4
1
2
3
4