python小记

基础

ord() 获取字符的整数表示
chr() 把编码转换为对应的字符

计算机内存中, 统一使用unicode编码,需要保存到硬盘或者
传说的时候,就转换为utf-8编码

b'ABC' 以字节为单位的bytes(网络传输,保存磁盘,只能包含ascii编码)

保存为指定的bytes

1
2
'asd'.encode('ascii')
'asd'.encode('utf-8')

以指定编码解码字节流

1
b'as'.decode('ascii',errors='ignore')

包含多少个字符

1
2
3
4
5
len('真好')
#2
转换成`bytes`, 计算的就是字节数
len('明天会更好'.encode('utf-8'))
#15

格式化

1
print("%s,真好-分数-%d-%.2f" %('试试',2,23.333))

list 和 tuple

1
2
3
4
5
6
7
8
9
10
11
12
13
classmates = ['kevin','lili','jobs']
追加
classmates.append('coco')
插入
classmates.insert(2,'stella')
删除
classmates.pop(1)
修改
classmates[0] = 'kevin.conan'

tp = (1,2,3)
tp2 = (1,)
tp3 = ()

条件判断

1
2
3
4
5
6
7
8
9
10
11
if a>10:
print('a>10')
else:
print('a<=10')

if b%2 == 0:
print('b is even')
elif b%3 == 0:
print('b % 3 == 0')
else:
print('''whats' ever...''')

强制类型转换

1
2
3
int('233')

str('233')

循环

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
39
40
41
for in [tuple or list]:

range(100)
生成0,1,2,3...99的list
sum = 0
for x in range(101):
sum += x
print(sum)

sum = 0
x = 100
while x>0:
sum += x
x = x - 1
print(sum)

dict 和 set

d = {"conan":27,'steve':49,'coco':31}
d['conan']
d['stella'] = 21

'conan' in d
# True

d.get('cssonan')
# 不存在则返回None

d.get('sss',-1)
# 自定义找不到时候的返回值

d.pop('stella')
删除一个键

s = set(range(10))
s.add(222)
s.remove(222)

s2 = set(range(20))
s2 & s 交集
s2 | s 并集

函数

1
2
3
4
5
def find_min(list):
return min(list)

def nop():
pass

返回多个值,实际上返回的是tuple

1
2
3
def rttp():
return 1,2,3
x,y,z = rttp();

内置类型检测函数

1
2
3
isinstance(type(1),type)
isinstance(1,(float,int))
isinstance(True,(float,int,bool))

参数

一般参数:

1
2
def func(x,y,z):
return x+y+z

默认参数

1
2
def func2(x,y=2,z=3):
return x+y+z

可变参数(内部tuple)

1
2
3
4
5
6
def func3(x,y=2,*z):
sum = 0
for a in z:
sum += a
return x+y+sum
func3(1,1,*[1,2,3,4])

关键字参数(内部dict)

1
2
3
4
5
6
7
8
9
10
def fun4(x,y=3,*z,**kw):
print(x,y,z,kw);
pass
fun4(1,2,3,**{'css':'asd'})
#1 2 (3,) {'css': 'asd'}
*args是可变参数,args接收的是一个tuple

**kw是关键字参数,kw接收的是一个dict

定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。

递归

1
2
3
4
5
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)

切片(含头不含尾)

1
2
3
4
5
6
7
L = [1,2,3,4,5]
L[:] 复制一遍
L[0:10]
L[:-1] 不包含最后一个
L[1:] 不包含第一个

L[::2] 每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
from collections import Iterable

isinstance([],Iterable)
# True

list,tuple,字符串,dict,

dict迭代的时候
迭代key
for key in dict:
pass
迭代value
for value in dict.values():
pass
一起迭代
for k,v in dict.items():
pass

enumerate 将list变成索引-元素对

for i,v in enumerate([1,2,3,4,5]):
pass

list(range(1,11));
#[1,2,3,4,5,6,7,8,9,10]

[x*x for x in range(1,11)]

生成器

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
g = ( x * x for x in range(10))
for n in g:
print(n)

迭代器
可直接用for循环的数据:
list,tuple,dict,set,str,
generator,包括生成器和带yield的generator函数
这些可用for循环迭代的对象统称 Iterable 对象
from collections import Iterable

isinstance([],Iterable)
isinstance({},Iterable)
isinstance('',Iterable)
isinstance((x for x in range(10)),Iterable)
#All Are True

Iterator 对象(能被next()调用迭代)
from collections import Iterator
isinstance((x for x in range(10)),Iterator)
#True
isinstance(iter('sad'),Iterator)
#True
isinstance(iter([]),Iterator)
#True

map 和 reduce

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
list(map(str,(1,2,3,4,5)))
#['1','2','3','4','5']


list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,9]))
#[1, 4, 9, 16, 25, 36, 49, 64, 81]

def add(x,y):
return x+y;
reduce(add,[1,2,3,4,5])

filter 和 sorted

def ft(x):
return x%2 == 0
list(filter(ft,[1,2,3,4,5]))
# [2, 4]

sorted([2,3,1,24,2,23,5])
# [1, 2, 2, 3, 5, 23, 24]

sorted([2,3,1,24,2,23,5],reverse=True)
# [24, 23, 5, 3, 2, 2, 1]

sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
# ['about', 'bob', 'Credit', 'Zoo']

匿名函数

1
2
3
4
5
6
lambda x: x*x
等价于
def f(x):
return x * x

list(map(lambda x:x*x,[1,2,3,4,5]))

装饰器(代码运行期间,动态增加功能的方式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import functools

def log(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print("call %s()" % func.__name__)
return func(*args,**kw)
return wrapper

带参数的装饰器
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
def now():
print('2028-12-3')

偏函数

1
2
3
4
5

import functools
int2 = functools.partial(int,base=2)

`

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student(object):
pass

conan = Student()
isinstance(conan,Student)
#True
class Student(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
bart = Student('bart',32)

获取对象信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type()
type('123') == str
type(234) == int
type(23.2) == float
type(24+3j) == complex

import types
def fn():
pass
type(fn) == types.FunctionType
type(abs) == types.BuiltinFuncitonType
type(lambda x:x*x) == types.LambdaType
type((x for x in range(10))) == types.GeneratorType

isinstance(Child,Parent)

获得对象的所有属性和方法

1
2
3
dir()

dir("ABC")

直接操作一个对象的状态

1
2
3
4
5
6
7
8
9
10
getattr(obj,key,None)
setattr(obj,key,value)
hasattr(obj,key)

__slots__

class Student(object):
__slots__ = ('name','score')

s = Student()

定制类

class Student(object):
def init(self, name):
self.name = name
def str(self):
return ‘Student object (name=%s)’ % self.name
repr = str

枚举

from enum import Enum

Month = Enum(‘Month’,(‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’, ‘Jun’, ‘Jul’, ‘Aug’, ‘Sep’, ‘Oct’, ‘Nov’, ‘Dec’))

错误处理

try:
r = 10/0
except Exception as e:
print(e.message)
finally:
print(‘finally…’)

记录错误
import logging

try:
someFunc()
except Exception as e:
logging.exception(e)

文件读写

try:
f = open(‘/path/to/file’,’r’)
print(f.read())
finally:
if f:
f.close()

等价于:
with open(‘/path/to/file’,’r’) as f:
print(f.read())

逐行读取
for line in f.readlines():
print(line.strip())

读取二进制文件
f = open(path,’rb’)

指定非utf8编码的文本文件
f = open(path,’r’,encoding=”gbk”)

忽略错误
f = open(path,’r’,encoding=’gbk’,errors=’ignore’)

写文件
f = open(path,’w’)
写二进制文件
f = open(path,’wb’)

f.write(‘xxx’)
f.close()

便捷方法:
with open(path,’w’) as f:
f.write(‘xxx’)

##os 模块
import os
os.name

os.environ.get(‘HOME’)

创建 删除文件夹
os.mkdir(‘path’)
os.rmdir(‘path’)

路径拼接
os.path.join(‘x’,’s’)
路径拆分
os.path.split(‘a/b/c’)
(‘a/b’,’c’)
获取后缀名
os.path.splitext(‘xxx/xx/xas/xsd.xt’)
重命名
os.rename(name1,name2)
os.remove(name1)

列出当前目录的文件夹
[x for x in os.listdir(‘.’) if os.path.isdir(x)]

列出当前目录的文件
[x for x in os.listdir(‘.’) if os.path.isfile(x)]

列出当前目录的py文件
[x for x in os.listdir(‘.’) if os.path.isfile(x) and os.path.splitext(x)[1]==’.py’]

序列化

import pickle
d = dict(name=’bob’,age=20,score=80)
pickle.dumps(d)
将对象序列化成bytes
or
f = open(‘dump.txt’,’wb’)
pickle.dump(d,f)
d.close()

f = open(‘dump.txt’,’r’)
pickle.loads(f.read())

JSON

import json
d = dict(name=’conan’,age=27,gender=’male’)
jsonstr = json.dumps(d)

new_dict = json.loads(jsonstr)

Class 转换为json对象
class Student(object):
def init(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def student2dict(st):
return {
‘name’:st.name,
‘age’:st.age,
‘gender’:st.gender,
}
json.dumps(s,default=student2dict)

json.dumps(s, default=lambda obj: obj.dict)

反序列化
def dict2student(d):
return Student(d[‘name’], d[‘age’], d[‘score’])
json_str = ‘{“age”: 20, “score”: 88, “name”: “Bob”}’
json.loads(json_str, object_hook=dict2student)

进程和线程

正则

import re

m = re.match(r’^([a-zA-Z][a-zA-Z0-9.]*)@[a-zA-Z0-9]+.[a-zA-Z]+’,'xxx@w21.com‘)
m.group(0)
原始字符串
m.group(1)
匹配的第一个分组
m.groups()
匹配到的结果元祖表示

re.split(r’\s+’,’a b v’)

编译使用
re_num_3 = re.compile(r’(\d{3})-‘)
re_num_3.match(‘332-12123’).groups()
(‘332’,)

常见内建模块

datetime
from datetime import datetime
now = datetime.now()
dt = datetime(2018,10,20,20,20)
now.timestamp()
datetime.fromtimestamp(now.timestamp())# 本地时间
datetime.utcfromtimestamp(now.timestamp())# UTC时间

字符串 datetime 互相转换
datetime.strptime(‘2018-10-20 18:22:22’,’%Y-%m-%d %H:%M:%S’)
now.strftime(‘%a, %b %d %H:%M’)

collections
from collections import namedtuple
Point = namedtuple(‘Point’,[‘x’,’y’])
p = Point(1,2)

from collections import deque
q = deque([‘a’,’b’,’c’])
q.append(‘x’)
q.appendLeft(‘y’)
q

#deque([‘y’, ‘a’, ‘b’, ‘c’, ‘x’])

from collections import defaultdict
dd = defaultdict(lambda: ‘N/A’)
dd[‘key1’] = ‘abc’

dd[‘key2’]

#’N/A’

from collections import OrderDict
OrderDict([(‘a’, 1), (‘b’, 2), (‘c’, 3)])

#key 是有序的

base64
import base64

c = base64.b64encode(b’binary content’)
d = base64.b64decode(c)
d.decode(‘utf-8’)

base64.urlsafe_b64encode(d)
base64.urlsafe_b64decode(c)

hashlib
import hashlib

md5 = hashlib.md5()
md5.update(‘that”s pretty awesome…’.encode(‘utf-8’))
md5.hexdigest()

sha1 = hashlib.sha1()
sha1.update(‘that”s pretty awesome…’.encode(‘utf-8’))
sha1.hexdigest()

hmac
import hmac
message = b’hello monkey’;
key = b’conan666’;
h = hmac.new(key,message,digestmod=”MD5”)
h.hexdigest()

第三方模块

pillow
requests
chardet
psutil

#chardet
data = chardet.detect(‘锄禾日当午’.encode(‘utf-8’))

#{‘encoding’: ‘GB2312’, ‘confidence’: 0.7407407407407407, ‘language’: ‘Chinese’}

import psutil
psutil.cpu_count()
psutil.virtual_memory()
psutil.swap_memory()

收发邮件

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(Header(name,’utf-8’).encode(),addr)

from_addr = 'conankyforce@163.com
password = ‘xxxx’
to_addr = 'xxx@22.com
smtp_server = ‘smtp.163.com’

msg = MIMEText(‘hello,send by python…’,’plain’,’utf-8’)
msg[‘From’] = _format_addr(‘Python爱好者 <%s>’ % from_addr)
msg[‘To’] = _format_addr(‘管理员 <%s>’ % to_addr)
msg[‘Subject’] = Header(‘来自SMTP的问候……’, ‘utf-8’).encode()

server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr,password)
server.sendmail(from_addr,[to_addr],msg.as_string())
server.quit()