Detailed explanation of various derivations in Python Programming

Keywords: Python less REST

Derivation formula

We've learned the simplest list derivation and generator expressions before. But in addition, there are dictionary derivation, set derivation and so on.

The following is a detailed derivation format with list derivation as an example, which is also applicable to other derivation.

variable = [out_exp_res for out_exp in input_list if out_exp == 2]
  out_exp_res:  List generates element expressions, which can be functions with return values.
  for out_exp in input_list:   iteration input_list take out_exp afferent out_exp_res Expression.
  if out_exp == 2:   Which values can be filtered according to the conditions.

List derivation

Example 1: all numbers within 30 that can be divided by 3

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

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' in the nested list

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, which is the key to implementation
 

 

Dictionary derivation

Example 1: swap the key and value of a dictionary

mcase = {'a': 10, 'b': 34}
mcase_frequency = {mcase[k]: k for k in mcase}
print(mcase_frequency)

Example 2: merge the value values corresponding to case, and unify k into lowercase

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 derivation

Example: calculate the square of each value in the list, with the function of de duplication

squared = {x**2 for x in [1, -1, 2]}
print(squared)
# Output: set([1, 4])

 

Exercise questions:

Example 1: filter out the list of strings less than 3 in length and convert the rest to uppercase letters

Example 2: find (x,y) where x is the even number between 0-5 and Y is the ancestor list composed of odd numbers between 0-5

Example 3: find the list m composed of 3,6,9 in M = [[1,2,3],[4,5,6],[7,8,9]]

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] 

Posted by Rony on Thu, 16 Apr 2020 07:08:51 -0700