Learn the comprehensions of Python every day.
The derivation simplifies the processing of data, making the code simple and very readable at the same time. This is often seen in Python.
List-derived
The list derivation allows all elements in the list to be uniformly manipulated to obtain a completely new list (the original list does not change), in [处理方式 for 元素 in 列表]
the form of which the processing can be done in whatever way:
>>>a=[1,2,3,4]>>>[i*2 forIincha][2,4,6,8]>>>a[1,2,3,4]>>>[(i*2, i+Ten) forIincha][(2, One), (4, A), (6, -), (8, -)]
The ability to filter out some elements of the original list by adding an If statement:
>>> a=[1,2,3,4]>>> [i*2forinif i>2][68]
Dictionary derivation type
We can create a dictionary by derivation, except that the parentheses of the dictionary derivation are curly braces:
>>> a[1234]>>> "str"forin a }{‘str3‘3‘str1‘1‘str4‘4‘str2‘2}
Using the dictionary derivation has a magical use, is the ability to exchange keys and values of the position:
a={‘one‘:1,"two":2,"three":3}>>> {valuefor key,valueina.items()}{1‘one‘2‘two‘3‘three‘}
Note: Ensure that values are immutable types, such as strings, tuples, etc.
Set Deduction formula
The set derivation is similar to the dictionary derivation. There is just one value instead of a key value pair:
>>> a={1,2,3,4,5}>>> {i**2forinif i%2==1}{1925}
Learn the comprehensions of Python every day.