[python] Use of generative expressions


  Comprehensions, also called derivation, are a concise expression method for generating regular data in Python. How to use the generation of a line of code to deduce the required data is a question often encountered in interviews.
  Note: List generation is the most basic generation in python, and other generation can be converted based on list generation .

1. String generation formula

String generators can be implemented via list generators:

>>> string = "".join([chr(i) for i in range(97,123)]) 
>>> string
'abcdefghijklmnopqrstuvwxyz'

Or it can be used with the ord function:

>>> "".join([chr(i) for i in range(ord("A"), ord("Z")+1)]) 
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

2. Tuple generation formula

Tuple generators are also implemented through list generators:

>>> tup = tuple([i for i in range(5)]) 
>>> tup
(0, 1, 2, 3, 4)
>>> type(tup)
<class 'tuple'>

3. List generation

3.1 Generate

List generators can be generated using generators (such as range, etc.) or other iterable objects:

>>> [i**2 for i in [0,1,2,3,4]]
[0, 1, 4, 9, 16]
>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

3.2 if statement

The list generator can also be used with the if function:
if the if function comes after it, it means filtering the for traversal results:

>>> [i for i in range(10) if i%2==1]
[1, 3, 5, 7, 9]

3.3 if-else statement

If the if function comes first, it means performing different operations on the traversal results of for. In this case, an else statement must be added:

# 奇变偶不变
>>> [i**2 if i%2==1 else i for i in range(10)] 
[0, 1, 2, 9, 4, 25, 6, 49, 8, 81]

This situation can be understood as performing a ternary operation on the result of for traversal, so it can also be implemented using the lambda function:

>>> [(lambda x:x**2 if x%2==1 else x)(i) for i in range(10)] 
[0, 1, 2, 9, 4, 25, 6, 49, 8, 81]

List comprehensions can also be implemented using generators:

>>> list(map(lambda x:x**2 if x%2==1 else x, range(10)))        
[0, 1, 2, 9, 4, 25, 6, 49, 8, 81]

4. Set generation formula

Just change the outer symbol of the production to "{}":

>>> [i for i in range(10) if i%2==1]
[1, 3, 5, 7, 9]

Of course, it can also be converted from list generation:

>>> set([i for i in range(10) if i%2==0]) 
{
    
    0, 2, 4, 6, 8}

Finally, it can also be obtained from the generative transformation:

>>> set(i for i in range(10) if i%2==0) 
{
    
    0, 2, 4, 6, 8}

5. Dictionary generation formula

It is also generated directly using "{}", but the "k:v" key-value pair is placed inside:

>>> {
    
    i:i**2 for i in range(10)} 
{
    
    0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

You can also extract data from a list to generate a dictionary:

>>> {
    
    i:j for (i,j) in [(1,1),(2,4),(3,9)]}  
{
    
    1: 1, 2: 4, 3: 9}

6. Other object generation formulas

For simple classes, simple generation can also be achieved through generative expressions.
Define a class Person:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Generate a list of classes:

names = ["张三", "李四", "王二", "麻子"]
ages = [34, 23, 56, 17]
person_list = [Person(names[i], ages[i]) for i in range(len(names))]

View the class elements in the list:

for person in person_list:
    print(f"name:{
      
      person.name}, age:{
      
      person.age}")
# name:张三, age:34
# name:李四, age:23
# name:王二, age:56
# name:麻子, age:17

Can’t tell the difference between generative formula and generator?
For more usage methods and applications of python, please pay attention to subsequent updates~

Guess you like

Origin blog.csdn.net/weixin_44844635/article/details/131378272