基于廖雪峰的 python 零基础学习后, 自我总结. 适用于有一定基础的编程人员, 对我而言, 则是基于. net 已有方面, 通过学习, 记录自我觉得有用的地方, 便于后续回顾.
主要以快速定位内容, 通过直观代码输入输出结果, 展示独有的特性, 更直观表现, 而不拘禁于理论描述. 待以后使用中遇到坑, 再来详细阐述.
本章包含, Python 基础, 函数, 高级特性, 函数式编程, 模块
一, Python 基础
Python 程序大小写敏感, 个人使用 sublime 编写程序, 注意规范使用 tab 缩进或者空格, 否则程序运行会报 unexpected error
字符串转义: 用 r''表示''内部的字符串默认不转义
- >>> print(r'\\\t\\')
- \\\t\\
用'''...'''的格式表示多行内容
>>> print('''line1
... line2
... line3''')
- line1
- line2
- line3
- Encode & Decode
- >>> 'ABC'.encode('ascii')
- b'ABC'
- >>> '中文'.encode('utf-8')
- b'\xe4\xb8\xad\xe6\x96\x87'
- >>> b'ABC'.decode('ascii')
- 'ABC'
- >>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
- '中文'
- >>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
- '中'
长度: len(str)
格式化: %s 字符串; %d 整数; %f 浮点数;%x 十六进制整数;%%=>%
- >>> print('%2d-%02d' % (3, 1))
- 3-01
- >>> print('%.2f' % 3.1415926)
- 3.14,
布尔值: True,False
空值: None
集合 list 和 元组 tuple
classmates = ['Michael', 'Bob', 'Tracy'] 集合 list append 添加, pop 删除
- classmates = ('Michael', 'Bob', 'Tracy')
- >>> classmates[-3]
- 'Michael'
- # 只有一个元素 tuple 定义加上逗号 ,
- >>> t = (1,)
- >>> t
- (1,)
- #"可变的"tuple 内部 list 改变, 实际指向 list 位置未变
- >>> t = ('a', 'b', ['A', 'B'])
- >>> t[2][0] = 'X'
- >>> t[2][1] = 'Y'
- >>> t
- ('a', 'b', ['X', 'Y'])
条件判断
- age = 20
- if age>= 6:
- print('teenager')
- elif age>= 18:
- print('adult')
- else:
- print('kid')
dic 字典 和 set
- >>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
- >>> d['Michael']
- 95
- # 设定默认值
- >>> d.get('Thomas', -1)
- -1
- # 删除
- >>> d.pop('Bob')
- 75
- # 重复元素在 set 中自动被过滤: add(key) remove(key)
- >>> s = set([1, 2, 3])
- >>> s
- {1, 2, 3}
二, 函数
函数定义
- def my_abs(x):
- if x>= 0:
- return x
- else:
- return -x
- # 返回多个值 return a,b,c
函数参数
- # 默认参数必须指向不变对象!
- def add_end(L=None):
- if L is None:
- L = []
- L.append('END')
- return L
- # *args 可变参数 ** 关键字参数
- def f1(a, b, c=0, *args, **kw):
- print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
- >>> f1(1, 2, 3, 'a', 'b', x=99)
- a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
- # *,d 命名关键字参数
- def f2(a, b, c=0, *, d, **kw):
- print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
- >>> f2(1, 2, d=99, ext=None)
- a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
- # 对于任意函数, 都可以通过类似 func(*args, **kw) 的形式调用它, 无论它的参数是如何定义的
三, 高级特性
切片 substring
- >>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
- >>> L[1:3] # L[1] L[2]
- ['Sarah', 'Tracy']
- >>> L = list(range(100))
- >>> L[-10:] # L[-10:100] 后 10 个
- [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
- >>> L[:10:2] # L[0:10:2] 前 10 个数, 每两个取一个
- [0, 2, 4, 6, 8]
- >>> L[:] # L[0:100:1] copy 复制
- [0, 1, 2, 3, ..., 99]
- >>> L[::-1] #相当于 L[-1:-101:-1] if s<0 then L[-1:-len(L)-1:-1]
- [99, 98, 97, ..., 0]
迭代 for
- >>> from collections import Iterable
- >>> isinstance('abc', Iterable) # str 是否可迭代
- True
- >>> isinstance([1,2,3], Iterable) # list 是否可迭代
- True
- >>> isinstance(123, Iterable) # 整数是否可迭代
- False
- >>> for i, value in enumerate(['A', 'B', 'C']):
- ... print(i, value)
- ...
- 0 A
- 1 B
- 2 C
列表生成式
- >>> [x * x for x in range(1, 11) if x % 2 == 0]
- [4, 16, 36, 64, 100]
- >>> L = ['Hello', 'World', 'IBM', 'Apple']
- >>> [s.lower() for s in L]
- ['hello', 'world', 'ibm', 'apple']
生成器 yield
- >>> L = [x * x for x in range(10)]
- >>> L
- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- >>> g = (x * x for x in range(10))
- >>> g
- <generator object <genexpr> at 0x1022ef630>
- # 使用 next(g) or for n in g 可迭代对象 g
- # 斐波拉契数
- def fib(max):
- n, a, b = 0, 0, 1
- while n <max:
- yield b
- a, b = b, a + b
- n = n + 1
- return 'done'
迭代器
- >>> from collections import Iterator
- >>> isinstance((x for x in range(10)), Iterator)
- True
- >>> isinstance([], Iterator)
- False
- >>> isinstance({}, Iterator)
- False
- >>> isinstance('abc', Iterator)
- False
- #Iterable. for 循环迭代
- #Iterator. next 迭代器
- # Iterable 转换 Iterator
- >>> isinstance(iter([]), Iterator)
- True
- >>> isinstance(iter('abc'), Iterator)
- True
四, 函数式编程
高阶函数 map/reduce/filter/sorted
- #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]
- # r 为 Iterator 惰性序列, list() 是整个序列返回
- #reduce reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
- >>> from functools import reduce
- >>> def add(x, y):
- ... return x + y
- ...
- >>> reduce(add, [1, 3, 5, 7, 9])
- 25
- #map reduce 结合使用
- from functools import reduce
- DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
- def char2num(s):
- return DIGITS[s]
- def str2int(s):
- return reduce(lambda x, y: x * 10 + y, map(char2num, s))
- #filter filter() 把传入的函数依次作用于每个元素, 然后根据返回值是 True 还是 False 决定保留还是丢弃
- def not_empty(s):
- return s and s.strip()
- list(filter(not_empty, ['A', '','B', None,'C',' ']))
- # 结果: ['A', 'B', 'C']
- #sorted sorted() 函数对 list 进行排序
- >>> 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
- <function lazy_sum.<locals>.sum at 0x101c6ed90>
- >>> f()
- 25
- # 典型闭包错误
- def count():
- fs = []
- for i in range(1, 4):
- def f():
- return i*i
- fs.append(f)
- return fs
- f1, f2, f3 = count()
- >>> f1()
- 9
- >>> f2()
- 9
- >> f3()
- 9
- ## 返回闭包时牢记一点: 返回函数不要引用任何循环变量, 或者后续会发生变化的变量
修改后:
- def count():
- def f(j):
- def g():
- return j*j
- return g
- fs = []
- for i in range(1, 4):
- fs.append(f(i)) # f(i) 立刻被执行, 因此 i 的当前值被传入 f()
- return fs
匿名函数 lambda
- >>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
- [1, 4, 9, 16, 25, 36, 49, 64, 81]
- #lambda 不包含 return, 返回即使 return 结果
装饰器
- import functools
- def log(text):
- def decorator(func):
- @functools.wraps(func)
- def wrapper(*args, **kw):
- print('%s %s():' % (text, func.__name__))
- return func(*args, **kw)
- return wrapper
- return decorator
- @log('execute')
- def now():
- print('2018-8-13')
- >>> now()
- execute now():
- 2018-8-13
偏函数
- >>> import functools
- >>> int2 = functools.partial(int, base=2)
- >>> int2('1000000')
- 64
- # 相当于下面这样调用
- kw = { 'base': 2 }
- int('10010', **kw)
五, 模块
来源: https://www.cnblogs.com/aikenwu/p/9471570.html