【Python】python学习之总结

 1 迭代器:
 2 def gen():
 3     a = 100
 4     yield a
 5     a = a * 8
 6     yield a
 7     yield 1000
 8 for i in gen():
 9     print(i)
10 创建一个函数,循环体,yield循环到此就返回一个值。调用函数,打印出循环结果:
11 100
12 800
13 1000
14 表推导:
15 L = [x**2 for x in range(10)]
16 print(L)
17 等价于:
18 M = []
19 for x in range(10):
20     M.append(x**2)
21 print(M)
22 打印出结果:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
23 xl = [1,3,5]
24 yl = [9,12,13]
25 L  = [ x**2 for (x,y) in zip(xl,yl) if y > 10]
26 print(L)
27 等价于
28 for (x,y) in zip(xl,yl):
29     if y > 10:
30         print(x)
31 我们可以先打印出zip对应的Y值大于10的X的值
32 打印出X的值:
33 >>3
34 >>5
35 打印出L的值:[9, 25]
 1 #lambda函数
 2 def test(f,a,b):
 3     print ('test')
 4     print(f(a,b))
 5 test((lambda x,y:x**2+y),6,9)
 6 #使用lambda匿名函数给f参数传递值,可以使不同形式的。
 7 打印结果:
 8 >>test
 9 (f(a,b))相当于a=6传递给x,b=9传递给y,组合成f的值
10 >>45
11 #map()
12 re = map((lambda x:x+3),[1,3,5,7])
13 print(list(re))
14 #map中的一个参数x,将后面列表中的值一次传递给x,相当于列表的值依次加3,在取值中以列表的形式。
15 打印结果:
16 [4, 6, 8, 10]
17 re2 = map((lambda m,n:m**n),[1,2,3,4],[5,6,7,8])
18 print(list(re2))
19 打印结果:
20 [1, 64, 2187, 65536]
21 #filter()
22 def abc(a):
23     if a > 100:
24         return True
25     else:
26         return False
27 newlist = filter(abc,[100,30,101,200])
28 print(list(newlist))
29 #创建一个函数abc中有一个参数a。newlist中函数filter将列表的值一次传给函数abc中的参数a,取值用列表形式。
30 打印结果:
31 [101, 200]
32 #reduce()
33 #from functools import reduce  #因为python不支持reduce函数,可以在functools库中导入单个reduce函数
34 import functools #可以直接导入整个库
35 print(functools.reduce(lambda x,y:x+y,range(1,101)))
36 #reduce函数是将列表中的值的第一次传递两个参数相加的和3,在传递一个参数3相加。相当于1-100相加的和。
37 打印结果:
38 >>5050

 

posted @ 2017-10-27 16:16  杨浪  阅读(252)  评论(0编辑  收藏  举报