注:object是所有类的基类,python中一切皆对象,类也是对象
1.取商和余数
divmod(10,3)
#输出(3,1)
2.次幂
pow(3,2,4)
#输出1
3.任意对象转为字符串
str()
4.计算字符串的表达式
eval(s)
5.对可迭代对象排序
a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'xiaohong','age':20,'gender':'female'}]
sorted(a,key=lambda x: x['age'],reverse=False)
#输出 [{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]
6.求和
sum()
7.nonlocal用于内嵌函数中,声明变量i为非局部变量
global声明全局变量
8.切片操作:slice()
9.dict()与zip()结合
dict(zip(['a','b'],[1,2]))
#输出 {'a': 1, 'b': 2}
10.集合,不允许有重复元素
set()
11.一键查看对象所用方法
dir(实例化对象)
12.对象是否有该属性
hasattr(对象,属性)
13.判断是否为类的实例
isinstance(对象,类)
14.类的类被称为:元类
Student = type('Student',(),{})
15.枚举对象:enumerate()
16.查看变量所占字节数
import sys
a = {'a':1,'b':2.0}
sys.getsizeof(a)
#输出:占用240个字节
17.过滤器
fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
list(fil)
#输出:[11, 45, 13]
18.返回对象的哈希值,自定义的实例都是可哈希的,list,dict,set等可变对象都是不可哈希的
hash(实例)
19.一键帮助:
help(实例)
20.创建迭代器:对可迭代对象用iter()
21.打开文件:
f = open()
f.read()
22.反向迭代器
rev = reversed([1,4,2,3,1])
for i in rev:
print(i,end=' ')
#输出:1 3 2 4 1
23.聚合迭代器
a = range(5)
b = list('abcde')
[str(y) + str(x) for x,y in zip(a,b)]
#输出:['a0', 'b1', 'c2', 'd3', 'e4']
24.链式操作
from operator import (add, sub)
def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)(a, b)
add_or_sub(1, 2, '-')
#输出:-1
25.对象序列化,接口间的调用或者发起的 web 请求,一般使用 json 串传输
class Student():
def __init__(self,**args):
self.ids = args['ids']
self.name = args['name']
self.address = args['address']
xiaoming = Student(ids = 1,name = 'xiaoming',address = '北京')
xiaohong = Student(ids = 2,name = 'xiaohong',address = '南京')
import json
with open(r'C:\Users\Administrator\Desktop\json.txt', 'w') as f:
json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False)
#输出:[
{
"address":"北京",
"ids":1,
"name":"xiaoming"
},
{
"address":"南京",
"ids":2,
"name":"xiaohong"
}
]
25.几个小例子
#去掉最小值和最大值
def score_mean(lst):
lst.sort()
lst1 = lst[1:(len(lst)-1)]
return round(sum(lst1)/len(lst1),1)
lst=[9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]
score_mean(lst)
#打印99乘法表
for i in range(1, 10):
for j in range(1, i+1):
print('%d * %d = %d' % (j, i, j * i) , end="\t")
print()
#全展开,用递归
from collections.abc import *
def flatten(lst, out_lst=None):
if out_lst is None:
out_lst = []
for i in lst:
if isinstance(i, Iterable): # 判断i是否可迭代
flatten(i, out_lst) # 尾数递归
else:
out_lst.append(i) # 产生结果
return out_lst
#输出:[1, 2, 3, 4, 5, 6]
#列表等分
from math import ceil
def divide(lst, size):
if size <= 0:
return [lst]
return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))]
r = divide([1, 3, 5, 7, 9,8,5,3],3)
print(r)
#输出:[[1, 3, 5], [7, 9, 8], [5, 3]]
#列表压缩
def filter_false(lst):
return list(filter(bool,lst))
r = filter_false([None,0,False,'',[],'nihao',[1,2]])
print(r)
#输出:['nihao', [1, 2]]
#选择最长的列表
def max_length(*lst):
return max(*lst,key=lambda x: len(x))
r = max_length([1,2,3],[4,5,6,7,8],[9,10])
print(f'最长的列表是{r}')
#输出:最长的列表是[4, 5, 6, 7, 8]
#求众数
def top1(lst):
return max(lst, default='列表为空', key=lambda v: lst.count(v))
lst = [1, 3, 3, 2, 1, 1, 2]
r = top1(lst)
print(f'{lst}中出现次数最多的元素为:{r}')
#输出:[1, 3, 3, 2, 1, 1, 2]中出现次数最多的元素为:1
#多表之最
def max_lists(*lst):
return max(max(*lst, key=lambda v: max(v)))
r = max_lists([1, 2, 3], [6, 7, 8], [4, 5])
r
#输出:8
#列表查重
def has_duplicates(lst):
return len(lst)==len(set(lst))
x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
has_duplicates(x) # False
has_duplicates(y) # True
#浮点数等差数列
def rang(start, stop, n):
start,stop,n = float('%.2f' % start), float('%.2f' % stop),int('%.d' % n)
step = (stop-start)/n
lst = [start]
while n > 0:
start,n = start+step,n-1
lst.append(round((start), 2))
return lst
rang(1,8,10)
#输出:[1.0, 1.7, 2.4, 3.1, 3.8, 4.5, 5.2, 5.9, 6.6, 7.3, 8.0]
#按条件分组
def bif_by(lst, f):
return [ [x for x in lst if f(x)],[x for x in lst if not f(x)]]
records = [25,89,31,34]
bif_by(records, lambda x: x<80)
#输出:[[25, 31, 34], [89]]
# map实现向量运算
lst1=[1,2,3,4,5,6]
lst2=[3,4,5,6,3,2]
list(map(lambda x,y:x*y+1,lst1,lst2))
#输出:[4, 9, 16, 25, 16, 13]
#值最大的字典
def max_pairs(dic):
if len(dic) == 0:
return dic
max_val = max(map(lambda v: v[1], dic.items()))
return [item for item in dic.items() if item[1] == max_val]
r = max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
print(r)
#输出:[('b', 5), ('d', 5)]
#合并两个字典
def merge_dict(dic1, dic2):
return {**dic1, **dic2}
merge_dict({'a': 1, 'b': 2}, {'c': 3})
#输出:{'a': 1, 'b': 2, 'c': 3}
# topn字典
from heapq import nlargest
# 返回字典d前n个最大值对应的键
def topn_dict(d, n):
return nlargest(n, d, key=lambda k: d[k])
topn_dict({'a': 10, 'b': 8, 'c': 9, 'd': 10}, 3)
#输出:['a', 'd', 'c']
#异位词
from collections import Counter
def anagram(str1, str2):
return Counter(str1) == Counter(str2)
anagram('eleven+two', 'twelve+one') # True 这是一对神奇的变位词
anagram('eleven', 'twelve') #False
#使用ChainMap合并字典
from collections import ChainMap
dic1 = {'x': 1, 'y': 2 }
dic2 = {'y': 3, 'z': 4 }
merged2 = ChainMap(dic1,dic2)
merged2['x'] = 10
merged2
#输出:ChainMap({'x': 10, 'y': 2}, {'y': 3, 'z': 4})
#命名元组提高可读性
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z']) # 定义名字为Point的元祖,字段属性有x,y,z
lst = [Point(1.5, 2, 3.0), Point(-0.3, -1.0, 2.1), Point(1.3, 2.8, -2.5)]
print(lst[0].y - lst[1].y)
#输出:3.0
#样本抽样
from random import randint,sample
lst = [randint(0,50) for _ in range(100)]
print(lst[:5])# [38, 19, 11, 3, 6]
lst_sample = sample(lst,10)
print(lst_sample)
#输出:[7, 30, 40, 12, 5]
[39, 39, 19, 45, 0, 10, 42, 29, 3, 1]
#重洗数据集
import random
lst = [random.randint(0,50) for _ in range(10)]
random.shuffle(lst)
lst
#设置随机种子
import random
a = [random.randint(0,50) for _ in range(10)]
random.seed(1)
random.shuffle(a)
a
#10个均匀分布的坐标点
from random import uniform
[(uniform(0,10),uniform(0,10)) for _ in range(10)]
#10个高斯分布的坐标点
from random import gauss
x = range(10)
y = [2*xi+1+gauss(0,1) for xi in x]
points = list(zip(x,y))
points
# chain高效串联多个容器对象
from itertools import chain
a = [1,3,5,0]
b = (2,4,6)
for i in chain(a,b):
print(i,end=' ')
#输出:1 3 5 0 2 4 6
# product 案例
def product(*args, repeat=1):
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
rtn = product('xyz', '12', repeat=3)
next(rtn)