Various derivation formulas in Python
Python various derivation expressions
List comprehension
List comprehensions can use data types such as range intervals, tuples, lists, dictionaries, and sets to quickly generate a list that meets specified requirements.
The syntax format of list comprehension is as follows:
[Expression for iteration variable in iterable object [if conditional expression] ]
example,
>>> list=[x**2 for x in range(10) if x%2==0]
>>> list
[0, 4, 16, 36, 64]
Multi-level derivation;
>>> list=[(x,y) for x in range(5) for y in range(5) if x%2==0 if y%2!=0]
>>> list
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
Dictionary derivation
Dictionary comprehensions are similar to list comprehensions. example,
>>> dict={"a":3,"b":5}
>>> dict2={k:v**2 for k,v in dict.items()}
>>> dict2
{"a": 9, "b": 25}
>>> dict={"a":3,"b":5}
>>> dict2={v:k for k,v in dict.items()}
>>> dict2
{3: "a", 5: "b"}
Set derivation
Set comprehensions are similar to dictionary comprehensions. example,
>>> set={x**2 for x in {1,2,3}}
>>> set
{1, 4, 9}