Python turn to line series 10: various derivations, generator expressions

1. Introduction

Comprehensions (also known as analytic) are a unique feature of Python. A deduction is a structure that can construct a new data sequence from one data sequence . There are three kinds of derivations, both of which are supported in Python 2 and 3:

  1. List comprehension
  2. Dict comprehension
  3. Set comprehension

The official introduction to the deduction is:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

The comprehension is composed of a single expression, the expression is accompanied by 0 or more for/if clauses, but there is at least one for clause. In this case, the elements of the new container are generated like this: treat each clause in the for or if clause as a block, nest from left to right, and calculate the expression so as to reach the innermost each time An element is generated when the layer of the block.

Second, the specific grammar

List comprehension []

  • Generate a list in the interval [0,30).
>>> multiples = [i for i in range(30)]
>>> print(multiples)
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>>
  • Generate a list that is divisible by 3 in the interval [0,30).
>>> multiples = [i for i in range(30) if i % 3 == 0]
>>> multiples
 [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

Dictionary comprehension {}

Use dictionary comprehension to exclude dictionary elements with key "1"

def Dict_comprehension_Test():
    src_dict = {
        "1": 'first',
        "2": 'second',
        "3": 'third'
    }
    exclude1_dict = {key:value for key, value in src_dict.items() if key != "1"}
    print(src_dict)
    print(exclude1_dict)

Output result:

{'1': 'first', '2': 'second', '3': 'third'}
{'2': 'second', '3': 'third'}

Set comprehension {}

def Set_comprehension_Test():
    list_src = [1,1,2]
    set_seq={i**2 for i in list_src}
    print(set_seq)
    print(type(set_seq))

Output result:

{1, 4}
<class 'set'>

The difference with the former:

  1. Different from the list comprehension, the set comprehension uses the symbol {} (curly brackets) ;
  2. Unlike dictionary comprehensions, set comprehensions do not have key-value pairs ;

Generator expression

         The same syntax, using () --- parentheses will generate a generator .

>>> lista=[1,2,3,4,5,6]
>>> test_gen=(i for i in lista if i !=3 )
>>> print(test_gen)
<generator object <genexpr> at 0x028C6E70>
>>> next(test_gen)
1
>>> next(test_gen)
2
>>> test_gen.__next__()
4
>>>

Advantages of using comprehensions/generators

  1. Simplify code writing;
  2. Improve operational efficiency

For example, find the sum of the squares of all natural numbers in range (0, 10).

  • Possible ways of using generative expressions:
>>> sum_a = sum(x*x for x in range(0,10))   
>>> sum_a
285
  • A possible way to write without generating a formula is:
def sum_power_ten():
    src = range(0, 10)
    sum = 0
    for i in src:
        sum += (i*i)
    print(sum)

Compared:

         The code that does not use the generative formula uses the temporary variable src to store the range, and then uses the for loop to traverse the range range. The code is much more complicated than the generative formula.

Guess you like

Origin blog.csdn.net/zhaogang1993/article/details/89070020