自定义特殊方法:
from random import choice
class Zhipai:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = '梅花 方片 红桃 黑桃'.split( )
kings = '大王 小王'.split( )
def __init__(self):
self.cards = [(rank,suit) for rank in self.ranks for suit in self.suits ]
[self.cards.append(self.kings[i]) for i in range(len(self.kings))]
def __len__(self):
return len(self.cards)
def __getitem__(self,position):
return self.cards[position]
a = Zhipai()
for i in range(54):
print(f"第{i+1}张牌为 :",end=" ")
print(a[i]) #对__getitem__()方法的调用
print(choice(a)) #随机抽取一张纸牌
print(a[:])
print(('3','黑桃') in a)
自定义数据类型:以二维为例
from math import hypot
#实现二维向量类
class Vector:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r,%r)' %(self.x,self.y)
def __add__(self,other_Vector):
return Vector(self.x+other_Vector.x,self.y+other_Vector.y)
def __abs__(self):
return hypot(self.x,self.y)
def __mul__(self,numm):
return Vector(self.x*numm,self.y*numm)
def __bool__(self):
return bool(self.x or self.y)
def __truediv__(self,numm):
return Vector(self.x/numm,self.y/numm)
a_1 = Vector(2,4)
a_2 = Vector(1,3)
print((a_1 + a_2)/2)
print((a_1 + a_2)*2)
print(abs(Vector(1,-1)))
列表推导式和生成器推导式:
import array,os
from collections import namedtuple
symbols = [0,1,4]
symbols_1 = [symbol for symbol in symbols if symbol >=1] #列表推导式,基础问题,不细说
a = tuple(symbol for symbol in symbols) #生成器表达式,遵守迭代器协议,节省列表推导式所占用空间,即逐个产生元素而不是全部一次性创建
#print(a)
m = 'acv'
#print(array.array('f',(ord(symbol) for symbol in m)))
id_s = [('china','0818222'),('usa','0718241')]
for xx in sorted(id_s):
print('%s/%s'%xx)
address = (-34.112,118.452)
address_r,address_l = address #元组拆包
e,q,*rest = symbols #*rest 用来获取剩余的不确定数量的元素
#print(e,*rest,q)
#嵌套元组拆包
address_com = (-34.112,118.452,(-10,50))
a,b,(c,d) = address_com
#print(c)
#具名元组,使用工厂函数构建
City = namedtuple('City','name pop lanlong') #传入类名和字段名
xi_an = City('XIAN','2000w', (-50,50)) #传入参数
#print(xi_an.pop,xi_an[2]) #通过字段名或位置索引字段信息
a = City._fields #City类的所有字段名称的元组
bei = ('Beijing','3000w',(-25.124,66.885))
beijing = City._make(bei) #City._make()传入可迭代对象来生成类实例
c = beijing._asdict() #._asdict() 实例方法,把具名元组以字典形式返回
print(c)
列表切片以及序列操作:
import numpy as np
import dis
bike = list('bicycle')
bike_0 = bike[::-1] #对对象全切,反向输出
bike_1 = bike[::2]
bike_2 = bike[slice(1,3)] #切片对象slice(a,b)
#切片赋值
bike[1:3] = ['a0O'] #右侧必定为可迭代对象
print(bike)
#列表的重复叠加,注意指向问题
a = [1,2,3]
b = (1,2,3)
print(id(a),id(b))
a+=[2]
b*=2
print(a,id(a),id(b)) #不可变元组的增量乘法为:创建新的元素
t = (1,[2,3])
try:
t[1] += [1,1]
except:
print(t) #这是最神奇的地方哈哈,即有错误被抛出,但t【1】依然被改动
t[1].extend([10,20])
print(t)
print(dis.dis('a += [2.3]'))
#①增量赋值不是原子操作,②不要把可变元素放入不可变元组中,③注意查看python字节码
序列排序方法:
import sys,bisect,random
from array import array
a = (1,222,31)
b = sorted(a) #sorted()对任何序列的排序返回值都是列表,原来的序列(a)不改变
c = b.append(151)
print(b)
d = b.sort(reverse=False) #list.sort()将直接在原序列上操作
print(b,a)
handle = [1,2,4,6,9,15,85,100,120,121]
position = bisect.bisect(handle,7) #返回插入位置值bisect_right和bisect_left的区别:插入目标位置的右/左
#由分数查成绩
def grade_find(score,point=[60,70,80,90],grade='edcba'):
position = bisect.bisect(point,score)
grad = grade[position]
return grad
grades = [grade_find(i) for i in [50,52,80,95,0,100]]
#print(grades)
a = []
for i in range(20):
b = random.randrange(150)
bisect.insort(a,b)
print(f'{i}:-->',end=' ')
print(a) #insort()函数可以保证插入后的序列依然为有序的
#当列表不是首选时:数组,内存视图,numpy和scipy,双向队列等队列形式
ff = array('d',(random.random() for i in range(10**7))) #数组
fd = array('d')
with open('千万浮点数.bin','wb') as fn:
ff.tofile(fn)
with open('千万浮点数.bin','rb') as fp:
fd.fromfile(fp,10**7)
print(ff==fd)
numpy数组初识,双向队列(大大减少程序运行时间):
import array,numpy
from collections import deque
numbers = array.array('h',[-1]) #创建数组
numbers_1 = memoryview(numbers)
mem = numbers_1.cast('B')
print(mem.tolist())
mem[1] = 4 #直接修改数组字节
print(numbers)
a = numpy.arange(12).reshape(3,4)
print(a.transpose()) #矩阵的转置
print(a[:,:3]) #前三列
#以上为扁平序列numpy数组和标准数组。以下为另一种数据结构:队列
#普通的list列表有append()和pop(),类似于栈,有进出的顺序,而双向队列可以更快的在左侧插入
queue = deque(numpy.arange(6),maxlen=6) #建立双向队列queue
queue.rotate(2) #旋转参数n=2,队列向右移动2
queue.appendleft(10) #对已满队列添加元素时,会删除队尾
queue.extend([20,21]) #挤掉左侧元素
queue.extendleft([20,21]) #挤掉右侧元素
print(queue)
敬请批评指正。