The derivation of comprehensions (also known as analytic) is a unique feature of Python. Derivation is the structure of another new data series that can be built from one data series.
- List-derived
- Dictionary (dict) derivation formula
- Set (set) derivation
List derivation one, use [] to generate list
Basic format
for inch if the condition]expression# list generates an element expression, which can be a function with a return value. the for in iterable # Iteration iterable the item into expression expressions. if condition # Filters data based on conditions, generating desired data
Eg: List-generated
for inch if Item% 2 = = 0]print(VAR)
# output
[0, 2, 4, 6, 8] # Output as List
Second, use () to generate generator
Convert the list derivation [] to () to get the generator
Eg: generator expression
gen= ('egg%s'for inif i > 5) print (gen)
Print (List (gen))
# output
<generator object <genexpr> at 0x7f4b7c219d58> # Builder Objects
[' Egg6 ', ' Egg7 ', ' Egg8 ', ' egg9 '] # Data inside the generator
Dictionary derivation type
Dictionary derivation and list derivation are used in a similar way, except that the brackets should be changed to curly braces. Direct illustrative examples
Eg: uppercase and lowercase key merging
Mcase = {'a': 10,'b': 34,'A': 7,'Z': 3}mcase_frequency={k.lower (): Mcase.get (K.lower (), 0)+Mcase.get (K.upper (), 0) forKinchMcase.keys ()ifK.lower ()inch['a','b']}Printmcase_frequency#Output Results{' A ': +, ' B ':
Eg: Quick change of key and value
Mcase = {'a'b': in Mcase.items ()}print mcase_frequency
# Output Results {ten: ' A ', ' C ': ' B '}
Set Deduction formula
is similar to the list derivation. The only difference is that it uses curly braces {}.
eg
for inch [1, 1, 2]} Print (squared) # Output Results # Output:set ([1, 4])
Python full stack development: Derivation of Python (list derivation, dictionary derivation, set deduction)