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. There are three kinds of derivation, which are supported in Python2 and 3:
- List-derived
- Dictionary (dict) derivation formula
- Set (set) derivation
First, the list deduction formula
1. Use [] to generate list
Basic format
for inch if out_exp = = 2] out_exp_res: The list generates an element expression, which can be a function with a return value. for inch input_list: Iteration input_list the out_exp into the out_exp_res expression. if out_exp = = 2: Filter which values can be based on conditions.
Example one:
for inch if is 0] Print (multiples) # Output: [0, 3, 6, 9, (+), (+) ,-
Example two:
def squared (x): return x*for onif is 0]print Multiples# Output: [0, 9, $, Bayi, 144, 225, 324, 441, 576, 729]
2. Use () to generate generator
The generator can be obtained by changing the two-table derivation [] to ().
for inch if is 0) Print (Type (multiples)) # Output: <type ' generator ' >
Second, the dictionary derivation formula
Dictionary derivation and list derivation are used in a similar way, except that the brackets should be changed to curly braces. The direct example illustrates:
Example one: Capitalization key merge
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: {' A ': +, ' B ':
Example two: Quick change of key and value
Mcase = {'a'b': in Mcase.items ()}print mcase_frequency# Output: {: ' A ',: ' B '}
Three, set deduction formula
They are similar to the list derivation. The only difference is that it uses curly braces {}.
Example one:
for inch [1, 1, 2]} Print (squared) # Output:set ([1, 4])
Various derivation formulas of Python (list derivation, dictionary derivation, set deduction)