A simple example

Given that the list a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] requires you to increment each value in the list by 1. How do you do that?

Stupid teen version

Create a new list B, iterate through list A, increment each value by one and store it in B, and finally set a=b

"" Of course there will be difficulties on the way to learning Python. How can you learn without good materials? Q group number: 928946953, a group of like-minded friends, help each other, there are good video tutorials and PDF! And Daniel answers! """ a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [] for i in a: b.append(i+1) b = a print(a) print(b) #Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Copy the code

Python

The reason for this double B is obvious: new lists are generated, wasting memory space

Regular youth edition

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index,i in enumerate(a):
    a[index] +=1
print(a)
#Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

Python

Nothing new

A little bit of a loser

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = map(lambda x:x+1, a)
print(a)
#Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

Python

Lambda anonymous functions are used, which is a little bit more interesting

You know what? You’re a teenager

a = [i+1 for i in range(10)]
print(a)
#Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

Python

So this is called a list generator, so what’s the use? Is it just to play “B”?

List derivation

I think you know that writing code like this is a pain

ls = []
for i in ls:
    if i % 2 ==0:
        ls.append(i)
print(i)
#Output: [0, 2, 4, 6, 8]
Copy the code

Python

copy

This might be fine for C, but in Python it is slow because the interpreter determines which part of the sequence needs to be changed on each loop, counters are needed to track which elements need to be processed, and each iteration requires an additional query function because of the append() method

List comprehensions solve these problems by automating parts of the above syntax with choreographed functionality

ls = [i for i in range(9) if i % 2 ==0]
print(i)
#Output: [0, 2, 4, 6, 8]
Copy the code

Python

Clearly, list comprehensions are not only more efficient, they are shorter, involve fewer syntactic elements and, in large programs, cause fewer errors

The basic grammar

Let’s look at the example given above

ls = [i for i in range(9) if i % 2 ==0]

We write the list derivation inside square brackets, because it ultimately builds a list. The list derivation consists of three main parts:

  1. For loop header for I in range(9)
  2. If I % 2 ==0
  3. The loop variable I is not very Ease very Amazing!

The working principle of

When Python executes a list derivation, it iterates over the iterable ls, assigns the value of each iteration to the loop variable I, and then evaluates it by if, finally

These results form the new list, which is the value returned by the list derivation

List comprehensions can be used on any object that supports iterating through a for loop

Dictionary derivation

Dictionary derivations are used in a similar way to list derivations, except that braces are used. Dictionary derivations are more often used for key and value swaps, merging value values that correspond to case and case

Merge value values corresponding to case

dt = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} dt_sum = { k.lower(): dt.get(k.lower(), 0) + dt.get(k.upper(), 0) for k in dt.keys() if k. power () in ['a','b']} #lower() upper() Print (dt_sum) #Output: {'a': 17, 'b': 34} #Output: {'a': 17, 'b': 34}Copy the code

Python

Quickly replace keys and values

dt = {'a': 10, 'b': 34} dt_change = {v: Print (dt_change) #Output: {10: 'a', 34: 'b'}Copy the code

Python

Set derivation

If you want to remove duplicate data, then you can use set comprehensions

sl = {i**2 for i in range(-2, 3)}
print(sl)
#Output: {0, 1, 4}
Copy the code

Python

conclusion

The derivation may seem unorthodox because it uses a for loop inside square brackets, but it makes the code much cleaner, especially because it can use “judgment conditions” to determine when to insert a new value

Derivations can help us filter or process the elements of a sequence or other iterable type into lists, dictionaries, and tuples. The combination of Python’s built-in filter and map functions can also achieve this effect, but the readability is significantly reduced

If you want to do the same thing in shorter code, you’ll need to master all three of these derivations