python基础知识回顾

时间:2019-02-28 22:36:08   收藏:0   阅读:163

参考教程  

 (一)数据类型

(二)list、tuple、dict、set

(三)基本逻辑

(四)函数

(五)生成器

>>> g = (x * x for x in range(10))
方法1:使用next()
>>> next(g) 0 >>> next(g) 1
方法2:使用循环
>>> for n in g:
...     print(n)
... 
0
1
4
9

一般函数顺序执行,遇到return返回,
生成器在每次调用next()时执行遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return ‘done‘
(五)迭代器 
可以被next()函数调用并不断返回下一个值的对象被称为迭代器,生成器都是迭代器对象。
list、tuple、dict、set、str需要使用iter()函数来变成迭代器

(六)高阶函数
>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]

 

 

 

原文:https://www.cnblogs.com/yuxiaowu/p/10452109.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!