Deduced routine
We have learned the simplest list comprehensions and generator expressions before. But in addition, there are actually dictionary derivation, set derivation, etc.
The following is a detailed format of the derivation type using the list derivation as an example, which is also applicable to other derivation types.
variable = [out_exp_res for out_exp in input_list if out_exp == 2] out_exp_res: list generation element expression, which can be a function with a return value. for out_exp in input_list: Iterate input_list and pass out_exp into out_exp_res expression. if out_exp == 2: According to the conditions, which values can be filtered.
List comprehension
Example 1: All numbers divisible by 3 within 30
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
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]
Example 2: The square of all numbers divisible by 3 within 30
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print(multiples)
Example 3: Find all names with two 'e's in the nested list
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] print ([name for lst in names for name in lst if name.count ('e')> = 2]) # Note the traversal order, this is the key to implementation
Dictionary comprehension
Example 1: swap the key and value of a dictionary
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
Example 2: Combine value values corresponding to upper and lower case, and unify k to lower case
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
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()} print(mcase_frequency)
Set comprehension
Example: Calculate the square of each value in the list, with its own deduplication function
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
squared = {x**2 for x in [1, -1, 2]} print(squared) # Output: set([1, 4])
Practice questions:
Example 1: Filter out a list of strings with a length less than 3, and convert the rest to uppercase letters
Example 2: Find (x, y) where x is an even number between 0-5 and y is an odd ancestor list between 0-5
Example 3: Find the list of 3,6,9 in M M = [[1,2,3], [4,5,6], [7,8,9]]
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1.[name.upper() for name in names if len(name)>3] 2.[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1] 3. [row[2] for row in M]