經過一行循環判斷,遍歷出一系列數據的方式就是推導式app
特色:方便,簡潔,能夠實現一些簡單的功能
推導式當中只能跟循環和判斷(單項分支)
種類分爲三種: 列表推導式 集合推導式 字典推導式
spa
#(1) 基本語法
#例:orm
#[1,2,3,4] => [2,4,6,8]
lst = [1,2,3,4]
lst2 = []
for i in lst:
res = i * 2
lst2.append(res)
print(lst2)
res = [i for i in range(1,5)]對象
print(res)索引
#[1, 2, 3, 4]three
#改寫
res2 = [i*2 for i in range(1,5)]
print(res2)
[2, 4, 6, 8]
#[1,2,3,4] => [2,8,24,64]
'''ip
解析:
1 ->2 乘以2的1次冪
2 ->8 乘以2的2次冪
3 ->24 乘以2的3次冪
4 ->64 乘以2的4次冪
'''
#把想要的值 寫在for的左側
res = [i<<i for i in range(1,5)] # 1<<1 2<<2 3<<3 4<<4
print(res)
#(2)帶有條件判斷的推導式
#例:it
lst = [1,2,3,4,5,6,67,7,8,98,9]
lst2 = []
for i in lst:
if i % 2 == 0:
lst2.append(i)
print(lst2)
#推導式寫法
res = [ i for i in lst if i % 2 == 0 ]
print(res)
#(3)多循環推導式
#例:io
lst1 = ["one","two","three","four"]
lst2 = ["five","six","seven","eight"]
lst = []
for i in lst1:
for j in lst2:
res = i +"♥♥♥"+j
lst.append(res)
print(lst)
res = [ i +"♥♥♥"+j for i in lst1 for j in lst2 ]
print(res)
#效果爲:form
['one♥♥♥five', 'one♥♥♥six', 'one♥♥♥seven', 'one♥♥♥eight', 'two♥♥♥five', 'two♥♥♥six', 'two♥♥♥seven', 'two♥♥♥eight', 'three♥♥♥five', 'three♥♥♥six', 'three♥♥♥seven', 'three♥♥♥eight', 'four♥♥♥five', 'four♥♥♥six', 'four♥♥♥seven', 'four♥♥♥eight']
#分析,one循環4次纔到下一個元素
#(4)帶有判斷條件的多循環推導式
#例:
lst1 = ["one","two","three","four"]
lst2 = ["five","six","seven","eight"]
lst_new = []
for i in lst1:
for j in lst2:
if lst1.index(i) == lst2.index(j) :
strvar = i + '♥♥♥' + j
lst_new.append(strvar)
print(lst_new)
#推導式方式實現:
res = [ i + '♥♥♥' + j for i in lst1 for j in lst2 if lst1.index(i) == lst2.index(j)]
print(res)
#在循環內加一個元素索引相等的判斷:lst1.index(i) == lst2.index(j)
#結果爲:
['one♥♥♥five', 'two♥♥♥six', 'three♥♥♥seven', 'four♥♥♥eight']
#(1){'x': 'A', 'y': 'B', 'z': 'C' } 把字典寫成x=A,y=B,z=C的列表推導式
dic = {'x': 'A', 'y': 'B', 'z': 'C' }
# for a,b in dic.items():
# print(a,b)
res = [a+"="+b for a,b in dic.items()]
print(res)
#(2)把列表中全部字符變成小寫 ["ADDD","dddDD","DDaa","sss"]
lst = ["ADDD","dddDD","DDaa","sss"]
res = [i.lower() for i in lst]
print(res)
#(3)x是0-5之間的偶數,y是0-5之間的奇數,把x,y組成一塊兒變成元祖,放到列表當中
#分析:
# (0 2 4)
# (1 3 5)
# (0 1) (0 3) (0 5)
# (2 1) (2 3) (2 5)
# (4 1) (4 3) (4 5)
lst_new = []
for i in range(0,6):
if i % 2 == 0:
for j in range(0,6):
if j %2 == 0:
lst_new.append((i,j))
print(lst_new)
#寫法一:
res = [(i,j) for i in range(0,6) if i % 2 == 0 for j in range(0,6) if j % 2 == 1]
print(res)
lst_new2 = []
for i in range(0,6):
for j in range(0,6):
if i % 2 == 0 and j % 2 == 1:
lst_new2.append((i,j))
print(lst_new2)
#寫法二:推導式方式表達
res = [(i,j) for i in range(0,6) for j in range(0,6) if i % 2 == 0 and j % 2 == 0]
print(res)
#(4)使用列表表達式 製做99乘法表的運算
#普通方法:
for i in range(1,10):
for j in range(1,i+1):
# print("%d*%d=%2d " % (i,j,i*j))
print("{:d}*{:d} ={:2d}".format(i,j,i*j),end="")
print()
#寫法一:推導式表達
res = ["{:d}*{:d} ={:2d}".format(i,j,i*j) for i in range(1,10) for j in range(1,i+1)]
print(res)
#普通方法:
for i in range(9,0,-1):
for j in range(1,i+1):
# print("%d*%d=%2d " % (i,j,i*j))
print("{:d}*{:d} ={:2d}".format(i,j,i*j),end="")
print()
#寫法二:推導式表達
res = ["{:d}*{:d} ={:2d}".format(i,j,i*j) for i in range(9,0,-1) for j in range(1,i+1)]
print(res)
(5)#求M,N中矩陣和元素的乘積
# M = [ [1,2,3],
# [4,5,6],
# [7,8,9] ]
# N = [ [2,2,2],
# [3,3,3],
# [4,4,4] ]
=>實現效果1 [2, 4, 6, 12, 15, 18, 28, 32, 36]
=>實現效果2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]]
M = [[1,2,3],[4,5,6],[7,8,9]]
N = [[2,2,2],[3,3,3],[4,4,4]]
#分析:
#M[0][0]*N[0][0] = 2
#M[0][1]*N[0][1] = 4
#M[0][2]*N[0][2] = 6
#
#M[1][0]*N[1][0] = 12
#M[1][1]*N[1][1] = 15
#M[1][2]*N[1][2] = 18
#M[2][0]*N[2][0] = 28
#M[2][1]*N[2][1] = 32
#M[2][2]*N[2][2] = 36
#效果1 #i => 0 1 2 j => 0 1 2 i動的慢 j 動的快
res = [M[i][j]*N[i][j] for i in range(3) for j in range(3)]
print(res)
#=> 效果2 [ [2,4,6] , [12,15,18], [28,32,36] ]
# [] [] []
'''
分析:
第一步遍歷三個空列表
[[] for i in rang(3)]
第二步 空列表裏面寫一個推導式對於的元素
[M[i][j]*N[i][j] for j in rang(3)]
'''
res =[ [M[i][j]*N[i][j] for j in range(3)] for i in range(3)]
print(res) #[[2,4,6] [] []]
3.
例:
知足年齡在18到21,存款大於等於5000 小於等於5500的人,
開卡格式爲:尊貴VIP卡老x(姓氏),不然開卡格式爲:摳腳大漢卡老x(姓氏)
把開卡的種類統計出來
listvar = [
{"name":"王家輝","age":18,"money":10000},
{"name":"王水機","age":19,"money":5100},
{"name":"王鵬","age":20,"money":4800},
{"name":"李站","age":21,"money":2000},
{"name":"李小龍","age":180,"money":20}
]
#res = {'a':1,'b':2}
#for i in res:
# print(i)
setvar = set()
for i in listvar:
if 18<=i['age'] <=21 and 5000 <i['money'] <= 5500:
strvar = '尊貴VIP卡老' + i["name"][0]
setvar.add(strvar)
else:
strvar = '摳腳大漢卡老' + i['name'][0]
setvar.add(strvar)
print(setvar)
#真值 if 條件表達式 else 假值
#第一部分 for i in listvar
#第二部分 三目運算 : "尊貴VIP卡老" + i["name"][0] if 18 <= i['age']<=21 and 5000<=i['money']<=5500 else "摳腳大漢卡老" + i['name'][0]
res = {"尊貴VIP卡老" + i['name'][0] if 18 <= i['age'] <= 21 and 5000 <=i['money'] <=5000 else "摳腳大漢卡老" + i['name'][0] for i in listvar}
print(res)
enumerate(iterable,[start=0])
功能: 枚舉 ; 將全部引號和iterable中的值,一個個拿出來配對組成元組放入迭代器中
參數:
iterable : 可迭代性數據(經常使用:迭代器,容器類型數據,可迭代對象range)
start: 能夠選擇開始的索引號(默認從0開始索引)
返回值: 迭代器
listvar = ["one","two","three","four"]
it = enumerate(listvar)
from collections import Iterable,Iterator
print(isinstance(it,Iterator))
#(1)使用next進行調用
res = next(it)
print(res)
res = next(it)
print(res)
#(2) 使用for來調用
for i in it:
print(i)
#(3)用list 瞬間獲得全部數據
it = enumerate(listvar)
lst = list(it)
print(lst) #[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')]
#利用enumerate變成字典推導式
res = {a:b for a,b in enumerate(listvar)}
print(res)
#使用dict強轉迭代器
res = dict(enumerate(listvar))
print(res)
功能:將多個iterable中的值,一個一個拿出來配對組成元組放入迭代器中
iterable:可迭代性數據(經常使用:迭代器,容器類型數據,可迭代對象range )
返回:迭代器
#(1) zip自動配對,若是長度超出了,自動捨棄
lst1 = ["one","two","three","four"]
lst2 = ["英俊瀟灑","瘋牛踢躺","柔情似水","摳腳大漢",1,2,3,4]
it = zip(lst1,lst2)
print(isinstance(it,Iterator))
#使用for 搭配next進行調用
for i in range(3):
res = next(it)
print(res)
for i in it:
print(i)
#利用zip實現字典推導式
res = {a:b for a,b in zip(lst1,lst2)}
print(res)
#使用dict強轉迭代器
res = dict(zip(lst1,lst2))
print(res)
#(2) 用兩個列表,實現以下字典:# 'xd':'熊大'# 'xe':'熊二'# 'gtq':'光頭強'dic1 = {'xd':"傻乎乎","xe":"呆呼呼","gtq":"光頭"}dic2 = {0:"熊大",1:"熊二",2:"光頭強"}lst_keys = dic1.keys()#print(lst_keys)#print(isinstance(lst_keys,Iterator))#print(isinstance(lst_keys,Iterable))lst_values = dic2.values()print(lst_values)#print(isinstance(lst_values,Iterable))#print(isinstance(lst_values,Iterator))it = zip(lst_keys,lst_values)print(it)#使用字典推導式實現res = {a:b for a,b in it}print(res)#使用dict強轉迭代器實現it = zip(lst_keys,lst_values)res = dict(it)print(res)