The derivation of Python
Push-to-go (list derivation, dictionary derivation, set deduction) for Python
Derivation formula: comprehensions (analytic type)
is a unique feature of Python, push-to-type is a data structure that can be used from a sequence component to another
三种推导式 1、列表推导式 2、字典推导式 3、集合推导式
• List-derived
1. Use [] to generate a list of lists
Basic format
V (variable) = [algorithm for each element for variable in iteration object if Boolean expression]
1. Algorithm: expression/function (with return value)
2. For variable in swipe to iterate over objects: each iteration of an element, assigned to a variable
Elements in a list ——-> expressions---> Elements
l=[i+1 for i in range(10)] print l#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3. If Boolean expression: based on conditional filter value
Note: If judgment can be omitted without making any judgment, other parts cannot be omitted
l=[i for i in range(10) if i%2==0] print l#[0, 2, 4, 6, 8]
2. Use () to generate the generator generator
Generator: Generator
l=(fun(i) for i in range(31) if i%3==0)print l#<generator object <genexpr> at 0x052DAA08>print type(l)#<type ‘generator‘>生成器
Instead of saving the results in a sequence, the generator saves the state of the generator, at each time
When iterating, returns a value until the end of the stopiteration exception is encountered.
The difference between a list deduction and a generator:
1、通过推导式直接创建所有的元素,占用空间大2、生成器相当于一个工具,创建列表的工具,更加省空间,用多少创建多少,只要不要超过上限
Characteristics
1、生成器本质也是一个可迭代对象(利用for循环进行遍历,for循环会调用next()方法)2、next():调用n次next的方法,创建n个元素l2=(i for i in range(100))print l2#<generator object <genexpr> at 0x052DAA08>l2.next()#0l2.next()#1l2.next()#2
Dictionary derivation formula:
Dictionary derivation and list derivation are used in a similar way
Create a form:
变量={ 键:值 for 变量 in 可迭代对象 if 布尔表达式}
Key value: Can be an expression, or it can be a function (a function with a return value)
d={str(i):i**2 for i in range(10) if i%3==0}d#{‘9‘: 81, ‘0‘: 0, ‘3‘: 9, ‘6‘: 36}#给定一个字典d1={‘one‘:1,‘two‘:2,‘three‘:3}请转换字典中的键与值d1 #{1: ‘one‘, 2: ‘two‘, 3: ‘three‘} for i in d1.iteritems(): #iteritems()返回键值对 ,如果直接在d1中可迭代,只是返回键。 print i#返回(‘three‘, 3) (‘two‘, 2) (‘one‘, 1) for key,value in d1.iteritems(): print key,value#返回 three 3 two 2 one 1 d1={value:key for key,value in d1.iteritems()} print d1#{1: ‘one‘, 2: ‘two‘, 3: ‘three‘}
Set Deduction formula
Definition form:
变量={ 表达式 for 变量 in 可迭代对象 if 布尔表达式}
Expression: can be a normal expression or a function (a function with a return value)
s={ i for i in range(10)if i%2==0}print s#set([0, 8, 2, 4, 6])
Python--012--derivation formula