Introduction to derivation in Python and introduction to Python Derivation
The derivation is a powerful and popular feature in Python. It has the advantages of concise language and fast speed. The Derivation includes:
NOTE:Dictionary and set derivation are recently added to Python (Python 2.7 and Python 3.1 and later versions). The following is a brief introduction:
List Derivation]
List derivation can easily construct a new list: only a concise expression can be used to convert and deform the elements.
The basic format is as follows:
[Expr for value in collection ifCondition]
The filtering condition is optional, depending on the actual application, leaving only the expression; equivalent to the following for loop:
result = []for value in collection: if condition: result.append(expression)
Example 1: Filter out the list of strings with a length less than 3 and convert the remaining strings to uppercase/lowercase letters.
>>> names = ['Bob','Tom','alice','Jerry','Wendy','Smith']>>> [name.upper() for name in names if len(name)>3]['ALICE', 'JERRY', 'WENDY', 'SMITH']
[Dictionary derivation]
The dictionary and the Set derivation are the continuation of this idea. The syntax is similar, but only the set and the dictionary are generated. The basic format is as follows:
{Key_expr: value_expr for value in collection ifCondition}
Example 1:Use dictionary derivation to create a dictionary with a string and its length
>>> strings = ['import','is','with','if','file','exception']>>> D = {key: val for val,key in enumerate(strings)}>>> D{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}
[Set derivation]
The Set derivation is very similar to the list derivation. The only difference is that {} is used instead of []. The basic format is as follows:
{Expr for value in collection ifCondition}
Example 1:Use a set to derive a set of string lengths
>>> Strings = ['A', 'is ', 'with', 'if', 'file', 'exception'] >>{ len (s) for s in strings} # set ([1, 2, 4, 9])
[Derivation of nested list]
The nested list refers to the nested list in the list, for example:
>>> L = [[1,2,3], [4,5,6], [7,8,9]]
Example 1:A nested list composed of a list of men and women. The name contains two or more letters e, which are displayed in the list.
names = [['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'], ['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]
Implement with a for Loop:
Tmp = [] for lst in names: for name in lst: if name. count ('E')> = 2: tmp. append (name) print tmp # output result >>> ['jefferson ', 'westsley', 'steven ', 'jennifer']
Implement with nested list:
>>> Names = [['Tom ', 'Billy', 'jefferson ', 'Andrew', 'westsley ', 'steven', 'Joe '], ['Alice ', 'jill', 'ana', 'wendy ', 'jennifer', 'sherry ', 'eva '] >>> [name for lst in names for name in lst if name. count ('E')> = 2] # Pay Attention to the traversal order. This is the key to implementation ['jefferson ', 'westsley', 'steven ', 'jennifer']