Catalog
The derived type (comprehensions)
List derivation (list comprehensions)
Dictionary derivation (dict comprehensions)
Set derivation (set comprehensions)
The derived type ( Also known as analytic ) yes Python A unique characteristic of , If I'm forced to leave it , I will miss you very much .
The derivation is that the structure of another new data sequence can be constructed from one data sequence . There are three kinds of derivation , stay Python2 and 3 There is support in :
We will discuss them one by one . Once you know the trick to using list derivation , You can easily use any derivation .
List derivation ( Also known as list parsing ) Provides a concise way to create lists .
Its structure is to include an expression in a square bracket , And then a for sentence , And then there was 0 One or more for perhaps if sentence . That expression can be arbitrary , It means you can put any type of object in the list . The result will be a new list , In this case, with if and for Statement is the expression of the context, which is generated after running .
standard
variable = [out_exp for out_exp in input_list if out_exp == 2]
Here is another concise example :
multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
This will be useful for quickly generating lists .
Some people even prefer to use it instead of filter function .
List derivation is great in some cases , Especially when you need to use for Loop to generate a new list . for instance , You usually do :
squared = []
for x in range(10):
squared.append(x**2)
You can use list derivation to simplify it , Just like this. :
squared = [x**2 for x in range(10)]
Dictionary derivation and list derivation are used in a similar way . Here's an example I found recently :
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {
k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
for k in mcase.keys()
}
result : mcase_frequency == {'a': 17, 'z': 3, 'b': 34}
In the above example, we combined the values of the same letter but different case .
Personally, I don't use a lot of dictionary derivation .
You can also quickly change the keys and values of a dictionary :
{v: k for k, v in some_dict.items()}
They are similar to list derivation . The only difference is that they use braces {}. for instance :
squared = {x**2 for x in [1, 1, 2]}
print(squared)
result : {1, 4}