1推导式列表 例1:整除3的数字列表 numbers=[] for x in range(100): if x%3==0: or numbers=[x for x in range(100) if x%3==0]: print(x) eg:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 例2: def squared(x): return x*x multiples=[squared(i) for i in range(30) if i%3 is 0] print(multiples) eg=[0,9,36,81,144,225,324,441,576,729] 例3:使用()生成generator将列表推导式的[]改成()即可得到生成器 multiples=(i for i in range(30) if i%3 is 0) print(type(multiples)) 2字典推导式 例1:快速更换key和value mcase={'a':10,'b':34} mcase_frequency={v:k for k,v in mcase.items()} print(mcase_frequency) eg:{10:'a',34:'b'} 3集合推导式(使用{}) 例1 squared={x**2 for x in [1,1,2]} print(squared) eg:{1,4} 例1:用集合推导字符串长度的集合 strings=['a','is','with','if','file','exception']{len(s) for s in strings}: print(strings) eg: squares=[] for x in range(10): print(x) eg:0 1 2 3 4 5 6 7 8 9 将单词长度大于3 的大写输出 names=['bob','tom','alice','jerry','wendy','smith'] print([name.upper() for name in names if len(name)>3]) eg:['ALICE','JERRY','WENDY','SMITH'] 例2求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表 [(x,y) for x in range(5) if x%2==0 for y in range(5) if y%2==1] print() eg: 例3求m 中3,6,9组成的列表 m=[[1,2,3],[4,5,6],[7,8,9]] print([row[2] for row in m]) eg:[3,6,9] 例4:求m中斜线1,5,9组成的列表 m=[[1,2,3],[4,5,6],[7,8,9]] print([m[i][i] for i in range(len(m))]) eg:[1,5,9] 例5 求m,n中矩阵各个元素的乘积 m=[[1,2,3],[4,5,6],[7,8,9]] n=[[2,2,2],[3,3,3],[4,4,4]] print([m[row][col]*n[row][col] for row in range(3) for col in range(3)]) eg:[2,4,6,12,15,18,28,32,36] print([[m[row][col]*n[row][col] for col in range(3)] for row in range(3)]) eg:[[2, 4, 6], [12, 15, 18], [28, 32, 36]] print([[m[row][col]*n[row][col] for row in range(3)] for col in range(3)]) eg:[[2, 12, 28], [4, 15, 32], [6, 18, 36]] 例6 结合两个列表的元素,如果元素之间不相等的话 combs=[] for x in [1,2,3]: for y in[3,1,4]: if x!=y: 推导:[(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y] print(x,y) eg:1 3 1 4 2 3 2 1 2 4 3 1 3 4 例7:创建列表 print([(x,x**2) for x in range(6)]) eg:[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
python的推导练习题
最新推荐文章于 2024-08-23 09:29:11 发布