Python学习(2)

来源:互联网 发布:上海网络电视台回看 编辑:程序博客网 时间:2024/06/14 05:26

本系列内容来源于 廖雪峰的Python教程 点击查看原文

迭代

dict 的迭代d = {'a':1,'b':2,'c':3}#遍历keyfor key in d:    print(key,end=" ")#遍历valuesfor key in d.values():    print(key,end=" ")#遍历key valuesfor k, v in d.items():    print(k,':',v,end=" ")c b a3 2 1c:3 b:2 a:1

列表生成式

形如:[表达式/x for x in range(0,10) 表达式][x for x in range(1,11)][x*x for in range(1,11)][x*x for in range(1,11) if x % 2 == 2]#两层循环>>> [m+n for m in 'ABC' for n in 'XYZ']  ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']#获取当前目录>>> import os>>> [d for d in os.listdir('.')]['Alice', 'AliceRobot', 'Android学习.txt', 'Bayes-master', 'CloudReader-master', 'd.jpg', 'desktop.ini', 'fnlp', 'fnlp-master', 'fnlp.zip', 'HttpClient.jar', 'learngit', 'NDK', 'RobotService.zip', 'textt.py']>>> L = ['Hello', 'World', 18, 'Apple', None]>>> [s.lower() for s in L if isinstance(s,str)]['hello', 'world', 'apple']

生成器

列表生成器

把列表生成式的[] 换成()通过next()去输出一次的结果>>> g = (x for x in range(10))>>> g<generator object <genexpr> at 0x0000016D28CBC728>>>> next(g)0>>> next(g)1>>> for x in g:    print(x,end=" ")2 3 4 5 6 7 8 9

生成器函数

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()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

高级函数

变量指向函数

>>> f = abs>>> f<built-in function abs>>>> f = abs>>> f(-10)10

map/reduce

map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回>>> 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]
reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算>>> from functools import reduce>>> def add(x, y):...     return x + y...>>> reduce(add, [1, 3, 5, 7, 9])

filter

filter()也接收一个函数和一个序列filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。def is_odd(n):    return n % 2 == 1list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

sorted

>>> sorted([36, 5, -12, 9, -21])[-21, -12, 5, 9, 36]根据key自定义排序>>> sorted([36, 5, -12, 9, -21], key=abs)[5, 9, -12, -21, 36]忽略大小写,并反向排序>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)['Zoo', 'Credit', 'bob', 'about']

返回函数

def lazy_sum(*args):    def sum():        ax = 0        for n in args:            ax = ax + n        return ax    return sum>>> f = lazy_sum(1, 3, 5, 7, 9)>>> f()25

匿名函数(lambda)

lambda x: x * x相当于def f(x):    return x * x

装饰器 请自行百度

偏函数

在 python的functools模块等int("10000",base=2)   #10000二进制 转换为十进制 base默认为10创建 偏函数>>> import functools>>> int2 = functools.partial(int,base=2)>>> int2('100000')32>>> int2('101001')41>>>
原创粉丝点击