列表解析
[x for x in data if x>= 0]
12 | [x for x in data if x>= 0] |
---|
filter函数:
g = filter(lambda x : x >=0, data) 在python3中,得到的是构造器,要用list才可以得到结果 list(g)
1234 | g = filter(lambda x : x >=0, data)在python3中,得到的是构造器,要用list才可以得到结果list(g) |
---|
字典解析
{k:v for k, v in d.items() if v> 90} d = {'student%d' %i :randint(50,100) for i in range(1,21)} {k:v for k,v in d.items() if v>=90}
12345 | {k:v for k, v in d.items() if v> 90} d = {'student%d' %i :randint(50,100) for i in range(1,21)}{k:v for k,v in d.items() if v>=90} |
---|
集合解析
{x for x in s if x%3==0}
12 | {x for x in s if x%3==0} |
---|
student = ('mubai',20,'male','1948877055@qq.com') 访问里面的数据用下标索引,可读性不好。
NAME,AGE,SEX,EMAIL = range(4) student[NAME] //mubai
123 | NAME,AGE,SEX,EMAIL = range(4)student[NAME] //mubai |
---|
//使用枚举 from enum import IntEnum class StudentEnum(IntEnum): NAME = 0 AGE = 1 SEX = 2 EMAIL = 3 student[StudentEnum.AGE] = 20 //使用collections.namedtuple from collections import namedtuple Student = namedtuple('Student',['name','age','sex','email']) s = Student('mubai',20,'male','1948877055@qq.com') //s.name = mubai
1234567891011121314 | //使用枚举from enum import IntEnumclass StudentEnum(IntEnum): NAME = 0 AGE = 1 SEX = 2 EMAIL = 3student[StudentEnum.AGE] = 20//使用collections.namedtuplefrom collections import namedtupleStudent = namedtuple('Student',['name','age','sex','email'])s = Student('mubai',20,'male','1948877055@qq.com')//s.name = mubai |
---|
根据成绩高低排名:
{
'LiLei':79,
'Jim':88,
'Lucy':92,
...
}
方案一:将字典中的项转化为(值,键)元组。(列表解析或zip )
//随机生成成绩表 from random import randint g = {k: randint(60,100) for k in 'abcdefgh'} //列表解析 d = [(v,k) for k,v in g.items()] //zip函数 d = list(zip(g.values(),g.keys()) m = sorted(d,reverse=True)
123456789 | //随机生成成绩表from random import randintg = {k: randint(60,100) for k in 'abcdefgh'}//列表解析d = [(v,k) for k,v in g.items()]//zip函数d = list(zip(g.values(),g.keys())m = sorted(d,reverse=True) |
---|
方案二:传递sorted函数的key参数
m = sorted(g.items(),key=lambda item:item[1],reverse=True)
12 | m = sorted(g.items(),key=lambda item:item[1],reverse=True) |
---|
最终排名:
n = list(enumerate(m,1)) //对m进行排序,加序号 for i,(k,v) in n: //迭代n,增加排序 g[k] = (i,v) //{'a': (1, 100), 'b': (7, 66), 'c': (8, 65), ...} o = {k:(i,v) for i,(k,v) in enumerate(m,1)}
12345 | n = list(enumerate(m,1)) //对m进行排序,加序号for i,(k,v) in n: //迭代n,增加排序 g[k] = (i,v) //{'a': (1, 100), 'b': (7, 66), 'c': (8, 65), ...}o = {k:(i,v) for i,(k,v) in enumerate(m,1)} |
---|
某随机序列找到出现次数最高的3个元素,它们出现次数是多少?
data = [randint(0,20) for _ in range(30)] //新建一个字典,值全为0 d = dict.fromkeys(data,0) //迭代,值加一 for x in data: d[x] += 1 m = sorted([(v,k) for k,v in d.items()],reverse=True) sorted(((v,k) for k,v in d.items()),reverse=True)[:3] //生成器解析 取前三个 //不用sorted全部计算,采用堆 import heapq m = heapq.nlargest(3,((v,k) for k,v in d.items()))
123456789101112 | data = [randint(0,20) for _ in range(30)]//新建一个字典,值全为0d = dict.fromkeys(data,0)//迭代,值加一for x in data: d[x] += 1m = sorted([(v,k) for k,v in d.items()],reverse=True)sorted(((v,k) for k,v in d.items()),reverse=True)[:3] //生成器解析 取前三个//不用sorted全部计算,采用堆import heapqm = heapq.nlargest(3,((v,k) for k,v in d.items())) |
---|
from collections import Counter c = Counter(data) //统计词频 c.most_common(3) //选前三
1234 | from collections import Counterc = Counter(data) //统计词频c.most_common(3) //选前三 |
---|
统计文本文件词频:
from collections import Counter text = open('a.txt').read() import re //正则表达式 word_list = re.split('\W+',txt) //非字符切割文本 t = Counter(word_list) t.most_common(10)
1234567 | from collections import Countertext = open('a.txt').read()import re //正则表达式word_list = re.split('\W+',txt) //非字符切割文本t = Counter(word_list)t.most_common(10) |
---|
场景:指定球员多场球赛进球数。 模拟:随机生成多个字典,找出公共建。
from random import randint,sample d = sample('abcdefgh',randint(3,6)) #进球的球员 d1 = {k:randint(1,4) for k in d} d2 = {k:randint(1,4) for k in d} d3 = {k:randint(1,4) for k in d} dl = [d1,d2,d3]
12345678910 | from random import randint,sample d = sample('abcdefgh',randint(3,6)) #进球的球员 d1 = {k:randint(1,4) for k in d}d2 = {k:randint(1,4) for k in d}d3 = {k:randint(1,4) for k in d}dl = [d1,d2,d3] |
---|
//循环迭代 for k in d1: if k in d2 and k in d3: print(k) //列表解析 [k for k in d1 if k in d2 and k in d3] [k for k in dl[0] if all(map(lambda d:k in d, dl[1:]))]
123456789 | //循环迭代for k in d1: if k in d2 and k in d3: print(k) //列表解析[k for k in d1 if k in d2 and k in d3][k for k in dl[0] if all(map(lambda d:k in d, dl[1:]))] |
---|
Step1:使用字典的keys()方法,得到一个字典keys的集合. Step2:使用map函数,得到每个字典keys的集合. Step3:使用reduce函数,取所有字典的keys集合的交集.
# reduce()函数介绍 //10的阶乘 from functools import reduce reduce(lambda a,b : a*b,range(1,11)) d1 = {k:randint(1,4) for k in d} d2 = {k:randint(1,4) for k in d} d3 = {k:randint(1,4) for k in d} d1&d3&d2 //下面是最终结果 reduce(lambda a,b:a&b,map(dict.keys,dl))
1234567891011 | # reduce()函数介绍//10的阶乘from functools import reducereduce(lambda a,b : a*b,range(1,11))d1 = {k:randint(1,4) for k in d}d2 = {k:randint(1,4) for k in d}d3 = {k:randint(1,4) for k in d}d1&d3&d2//下面是最终结果reduce(lambda a,b:a&b,map(dict.keys,dl)) |
---|
Python3.5之前的字典不是有序的,存和取位置并不是对应好的。 案例:编写根据排名获取选手的函数接口
from collections import OrderedDict players = list('abcdefgh') from random import shuffle #洗牌函数 shuffle(players) od = OrderedDict() for i,p in enumerate(players,1): od[p] = i #根据名字查询成绩 def query_by_name(d,name): return d[name] from itertools import islice def query_by_order(d,a,b=null): a -= 1 if b is None: b = a + 1 return list(islice(od,a,b)) query_by_order(od,3) query_by_order(od,3,6)
123456789101112131415161718192021 | from collections import OrderedDictplayers = list('abcdefgh')from random import shuffle #洗牌函数shuffle(players)od = OrderedDict()for i,p in enumerate(players,1): od[p] = i #根据名字查询成绩def query_by_name(d,name): return d[name] from itertools import islicedef query_by_order(d,a,b=null): a -= 1 if b is None: b = a + 1 return list(islice(od,a,b))query_by_order(od,3)query_by_order(od,3,6) |
---|
案例:现在我们制作了一个简单的猜数字的小游戏,如何添加历史记录功能,显示用户最近猜过的数字?
使用标准库collections中的deque,它是一个双端循环队列
from collections import deque q = deque([],5) //[]初始化 队列长度 q.append(1) //入队 q.appendleft(2) //从左入队 q.pop(1) //出队
123456 | from collections import dequeq = deque([],5) //[]初始化 队列长度q.append(1) //入队q.appendleft(2) //从左入队q.pop(1) //出队 |
---|
pickle.dump(obj, file, [,protocol]) 注解:将对象obj保存到文件file中去。
import pickle pickle.dump(q.open('save.pkl','wb')) #以二进制方式写入 p = pickle.load(open('save.pkl','rb')) #以二进制方式读取
1234 | import picklepickle.dump(q.open('save.pkl','wb')) #以二进制方式写入p = pickle.load(open('save.pkl','rb')) #以二进制方式读取 |
---|