Learn Python comprehensions every day
The derivation can simplify data processing and make the code concise and highly readable, which is very common in Python. List Derivation
List derivation allows you to perform a unified operation on all the elements in the list to obtain a new list (the original list does not change), as shown in[Processing Method for element in list]
The processing method can be any operation:
>>> a=[1,2,3,4]>>> [i*2 for i in a][2, 4, 6, 8]>>> a[1, 2, 3, 4]>>> [(i*2,i+10) for i in a][(2, 11), (4, 12), (6, 13), (8, 14)]
You can filter out some elements in the original list by adding the if statement:
>>> a=[1,2,3,4]>>> [i*2 for i in a if i>2][6, 8]
Dictionary Derivation
We can create a dictionary through the derivation, but the dictionary derivation brackets are curly brackets:
>>> a[1, 2, 3, 4]>>> { "str"+str(i):i for i in a }{'str3': 3, 'str1': 1, 'str4': 4, 'str2': 2}
The dictionary derivation has a wonderful use, that is, the location where keys and values can be exchanged:
>>> a={'one':1,"two":2,"three":3}>>> {value:key for key,value in a.items()}{1: 'one', 2: 'two', 3: 'three'}
Note: Make sure that the value is also of an unchangeable type, such as a string or a tuples.
Set Derivation
The Set derivation is similar to the dictionary derivation, but there is only one value instead of the key-Value Pair:
>>> a={1,2,3,4,5}>>> {i**2 for i in a if i%2==1}{1, 9, 25}