python高级

一、条件和循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
## if条件判断
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3

## while循环和while else语句
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")

## for循环
for <variable> in <sequence>:
<statements>
else:
<statements>

## range()函数 它会生成数列;range(4) 表述从0到4的税数列
for i in range(5,9) :
print(i)

## break和continue语句 与JAVA相同

## pass 语句
# Python pass是空语句,是为了保持程序结构的完整性。
while True:
pass # 等待键盘中断 (Ctrl+C)

二、迭代器与生成器

迭代器有两个基本的方法:iter()next()

1
2
3
4
5
6
7
8
9
10
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
print (x, end=" ")

while True:
try:
print (next(it))
except StopIteration:
sys.exit()

使用了 yield 的函数被称为生成器(generator),作用是函数执行时遇到这个关键字的时候就会停止执行,知道调用了next之后才能继续执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sys

def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成

while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()

三、函数

1
2
3
def 函数名(参数列表):
函数体
rturn ;

1. 参数

  • 必需参数
  • 关键字参数

    调用时:printinfo( age=50, name="light" );

  • 默认参数

    定义时:def printinfo( name, age = 35 ):

  • 不定长参数

    定义时:def printinfo( name, *str ):类似与java的...

  • 字典

    定义时:def printinfo( name, **args):

    2. 匿名函数

    python 使用 lambda 来创建匿名函数。

    1
    2
    sum = lambda arg1, arg2: arg1 + arg2;
    print ("相加后的值为 : ", sum( 10, 20 ))

3. global 和 nonlocal关键字

global局部变量修改全局变量的值

1
2
3
4
5
6
7
num = 1
def fun1():
global num # 需要使用 global 关键字声明
num = 123
print(num)
fun1()
print(num)

nonlocal关键字

1
2
3
4
5
6
7
8
def fun():
j = 0
def fun1():
nonlocal j
j = 5
print(j)
fun1()
print(j)

四、数据结构

1. python实现堆栈

1
2
3
4
5
6
7
8
9
10
# 堆栈:先进后出,后进先出
stack = [3, 4, 5]
stack.append(6) //压栈
stack.pop() //出栈

# 队列:先进先出
from collections import deque
queue = deque([1,2,3,4,56])
queue.append(6) # 添加到末尾
e = queue.popleft() # 取出队列中第一个参数

2. 列表推导式和遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
vec = [2, 4, 6]
result = [3*x for x in vec]
## return [6, 12, 18]
[[x, x**2] for x in vec]
## return [[2, 4], [4, 16], [6, 36]]

freshfruit = [' banana', ' loganberry ', 'passion fruit ']
[weapon.strip() for weapon in freshfruit]
## return ['banana', 'loganberry', 'passion fruit']

[3*x for x in vec if x > 3]
## return [12, 18]

vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
## return [8, 6, -18, 16, 12, -36, 24, 18, -54]
[vec1[i]*vec2[i] for i in range(len(vec1))]
## return [8, 12, -54]
[str(round(355/113, i)) for i in range(1, 6)]
## return ['3.1', '3.14', '3.142', '3.1416', '3.14159']
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[row[i] for row in matrix] for i in range(4)]
## return [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

## 列表转化为字典
dict(sape=4139, guido=4127, jack=4098)

## 遍历字典
for k, v in knights.items():
print(k,v)

## 遍历列表,带下标
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)

reversed(list) # 倒叙

五、模块

1
2
3
4
5
6
7
8
9
10
11
from modname import * # 把一个模块的所有内容全都导入到当前的命名空间,但是由单一下划线(_)开头的名字不在此例。
from fibo import fib, fib2
```

### `__name__`属性

```python
if __name__ == '__main__':
print('程序自身在运行')
else:
print('我来自另一模块')

每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入。

1
2
import fibo
v = dir(fibo) # return ['__name__', 'fib', 'fib2']

六、文件

1
2
3
4
5
6
7
8
9
10
f = open(filename, mode)    # 打开文件
f.read() # 读文件
f.readline() # 读一行
f.readlines() # 读所有的行
f.write('......') # 写文件
f.close() # 释放资源
f.writelines(sequence) # 写入多行

############os 模块############
os 模块提供了非常丰富的方法用来处理文件和目录

六、错误和异常

1
2
3
4
5
6
7
8
9
10

try:
f = 1/0
except:
print("我是错误")
raise ## 往外抛异常
else:
print("我没有报错")
finally:
print("我最终会执行")

预定义的清理行为

关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法

1
2
3
with open("myfile.txt") as f:
for line in f:
print(line, end="")

自定义异常

1
2
3
4
5
6
7
class MyError(Exception):
a = 'sf'
try:
i = 1/2
raise MyError('a', '')
except MyError :
print(MyError.a)

七、面向对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class A:
name = '父类的普通参数'
__name = '父类的私有参数'
# 定义私有属性,私有属性在类外部无法直接进行访问

# 定义构造方法
def __init__(self, name):
self.name = name
self.name2 = '这样也可以定义参数'
### 类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。
def fun(self,name):
self.__name = name
print('我是父类普通方法')

class B:
B_name = '我是B类的名称'
def __foo(self): # 私有方法
print('这是B类的私有方法')

class C(B,A): ## 多继承
def __init__(self,name):
A.__init__(self,name)
print(A.name)

## 也可以覆写父类的方法
def fun(self,name):
self.name = name
print('我要重写父类的方法')

def fun(self):
print('python不支持重载,但是这个方法生效,调用上面的方法将报错')

a = A('init_name')
print(a.name)
print(a.name2)
c = C(name='asd')
print(A.name)
super(C,c).fun('') # 调用父类的方法

八、Python3 标准库概览

操作系统接口

os模块提供了不少与操作系统相关联的函数。

1
2
3
4
5
6
7
8
import os
os.getcwd() # 返回当前的工作目录
os.chdir('/server/accesslogs') # 修改当前的工作目录
os.system('mkdir today') # 执行系统命令 mkdir

import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')

建议使用 “import os” 风格而非 “from os import *”。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。

文件通配符

1
2
3
import glob
glob.glob('*.py')
# return ['primes.py', 'random.py', 'quote.py']

命令行参数

1
2
import sys
print(sys.argv) # 打印运行脚本传进来的参数

字符串正则匹配

1
2
3
4
import re
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')

'tea for too'.replace('too', 'two') # 字符串替换

数字:import math

随机数:import random

访问 互联网

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
## URL访问
from urllib.request import urlopen
for line in urlopen('http://www.baidu.com'):
line = line.decode('utf-8')
print(line)

## 发送邮件
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""
To: jcaesar@example.org
From: soothsayer@example.org

Beware the Ides of March.
""")
server.quit()

日期和时间

1
2
3
4
5
6
from datetime import date
now = date.today()
print(now) # 输出 yyyy-MM-dd

nowdate = now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
print(nowdate) # 格式化输出

数据压缩

1
2
3
4
5
6
7
8
import zlib
s = b'witch which has which witches wrist watch'
# 字符串前面添加u代表是unicode字符串;r表示非转义的原始字符串 ;b是bytes的意思
print(len(s))
t = zlib.compress(s) # 压缩
print(len(t))
tt = zlib.decompress(t) # 解压
print(tt)

性能度量

1
2
3
4
5
from timeit import Timer
Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
## return 0.57535828626024577
Timer('a,b = b,a', 'a=1; b=2').timeit()
## return 0.54962537085770791

测试模块

1
# 待补充......
lightquant wechat
欢迎您订阅灯塔量化公众号!