python中可以使用推導式來通過已有的數據序列快速的創(chuàng)建一個數據序列。目前pyhton中有三種推到式填物。
- 列表
- 字典
- 集合
列表推導式
variable = [元素結果 for i in 已存在的list if 判斷條件]
元素結果可以為函數全庸,也可以為表達式,也可以為值融痛。
例如:
輸出值:
temp = [i for i in range(30) if i%3==0]
print(temp)//[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
表達式:
temp = [i**2 for i in range(30) if i%3==0]
print(temp)//[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
函數:
def iii(i):
i=i**3
return i
temp = [iii(i) for i in range(30) if i%3==0]
print(temp)//[0, 27, 216, 729, 1728, 3375, 5832, 9261, 13824, 19683]
字典推導式
variable = [k:結果值 for k in 已存在的dict if 判斷條件]
variable = [k,v for k,v in 已存在的dict.items() if 判斷條件]
輸出值:
dict1 = {'a':1,'b':2,'c':3}
temp ={ k:dict1.get(k,0) for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'c': 3}
表達式:
dict1 = {'a':1,'b':2,'c':3}
temp ={ k*2:dict1.get(k,0)**2 for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'cc': 9}
函數:
def iii(i):
i=i**3;
return i
def ii(i):
i=i*2
return i
dict1 = {'a':1,'b':2,'c':3}
temp ={ ii(k):iii(dict1.get(k,0)) for k in dict1 if dict1.get(k,0)%3 ==0}
print temp//{'cc': 27}
k,v值互換
dict1 = {'a':1,'b':2,'c':3}
temp ={ v:k for k,v in dict1.items() }
print temp//{1: 'a', 2: 'b', 3: 'c'}
集合
集合推導式與列表相似壶笼,只需把[]換成{}
例子
set1 = {1,1,1,2}
temp = {i for i in set1 if i-1>=0}
print(temp)//set([1, 2])