Dashuang Python introductory tutorial 6-3 container advanced generation

Teaching plan of open course for introduction to Dashuang Python Click to view the tutorial directory

Generative formula

How to quickly create a new list, such as a list of 0123456789.
According to the previous knowledge, we can use the range and list functions to generate.

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

But this method is actually quite limited. For example, it is not enough to generate the square of these data.

A more efficient method is introduced here, that is, comprehensions.
There are many kinds of generating expressions in python. Here, only two commonly used ones are introduced:

  • List completions
  • Dictionary completions

List generation

Basic grammar

Its basic syntax is

lst = [expression for item in iterable]

Its function is equivalent to

lst = []
for item in iterable:
    lst.append(expression)

that is

  1. Traversing iteratable object iterable
  2. Each time the traversed value is assigned to item,
  3. Use the expression expression expression to evaluate the item and add the value to the list.

The expression expression expression is very flexible,
For example, it can be a fixed value, an expression, or a function.
It can be related to or independent of item.

Examples are as follows

>>> [0 for i in range(5)]
[0, 0, 0, 0, 0]
>>> [i * i for i in range(5)]
[0, 1, 4, 9, 16]
>>> colors = ["red", "blue", "yellow", "green"]
>>> [len(s) for s in colors]  # Get the length of each string
[3, 4, 6, 5]

Advanced Grammar

This syntax is also commonly used

The advanced syntax of list generation is

lst = [expression for item in iterable if condition]

Its function is equivalent to

lst = []
for item in iterable:
    if condition:
        lst.append(expression)

That is, there are multiple conditions for conditional judgment,
expression is added to the list only when condition is true.

Examples are as follows

>>> lst = [1, -2, 3, -4, 6, 7, -8]
>>> [item for item in lst if item > 0] # Get all positive numbers
[1, 3, 6, 7]

For another example, we wrote a function to judge prime numbers before,
Combine this syntax here to obtain a list of all primes less than 100. The code is as follows

def is_prime(num):
    if num < 2:
        return False

    for i in range(2, num):
        if num % i == 0:
            return False

    return True

prime_100 = [num for num in range(100) if is_prime(num)]
print(prime_100)

The output is as follows

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Dictionary generator

In fact, dictionary generation is less used, and list generation is very much used.
The complete syntax of the dictionary generator is as follows

dic = {key: value for vars in iterable if condition}

It is equivalent to

dic = {}
for vars in iterable:
    if condition:
        dic[key] = value

Use examples are as follows

>>> {s: 0 for s in "abcde"}
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}
>>> fruits = [("apple",10), ("banana",5), ("cherry",20)]
>>> {item[0]: item[1] for item in fruits}
{'apple': 10, 'banana': 5, 'cherry': 20}

Using generative replication

It can also be implemented using generative expressions
Copy a list or dictionary

Examples are as follows

Copy list

>>> x = [1, 2, 3, 4]
>>> x_copy = [item for item in x]
>>> x_copy
[1, 2, 3, 4]

Copy dictionary

>>> a = {'apple': 10, 'banana': 5, 'cherry': 20}
>>> a_copy = {key: a[key] for key in a}
>>> a_copy
{'apple': 10, 'banana': 5, 'cherry': 20}

Added by kyin on Wed, 01 Dec 2021 19:54:36 +0200