01-字典列表集合中筛选 # 如何在列表字典集合中根据条件帅选数据 from random import randint # 第一种 # data = [-1,2,3,-4,5] # res = [] # for x in data: # if x 0: # res.append(x) # print(res) # a = randint(-10,10) #
from random import randint
# 第一种
# data = [-1,2,3,-4,5]
# res = []
# for x in data:
# if x > 0:
# res.append(x)
# print(res)
# a = randint(-10,10)
# print(a)
b = [randint(-10,10) for _ in range(10)]
# print(b)
# 第二种
# 列表解析
b2 = [x for x in b if x >= 0]
# print(b2)
# 第三种filter函数
# 返回一个生成器对象 next可以取出元素
b3 = filter(lambda x:x>=0,b)
# print(next(b3))
# print(list(b3))
# 第四种 字典
d = {'student%d' % i : randint(50,100) for i in range(1,21) }
# print(d)
# 获取分数高于90的学生
d1 = {k:v for k,v in d.items() if v >=90}
# print(d1)
g = filter(lambda item:item[1],d.items())
# print(list(g))
g = filter(lambda item:item[1],d.items())
# print(dict(g))
# 第五种集合
s = {randint(0,20) for _ in range(20)}
print(s)
s1 = {x for x in s if x %3 == 0}
print(s1)
View Code
02-枚举
# 举例from enum import Enum, unique
# @unique
# class Color(Enum):
# red = 1
# red_alias = 2
#
# print(Color['red'])
# print(Color.red.name)
# print(Color.red.value)
class Color(Enum):
red = 1
orange = 2
yellow = 3
green = 4
blue = 5
indigo = 6
purple = 7
red_alias = 1
for color in Color:
print(color)
for color in Color.__members__.items():
print(color)
print(Color['red'])
print(Color['red'].name)
print(Color['red'].value)
for i in Color:
print(i.name,'->',i.value)
View Code
03-具名元组
04-根据字典值的大小对字典中的项排序
#将字典中的各项转换为元组 使用内置函数sorted排序#包含元组的列表是可以排序的(元组是可以比较大小的)
# print((3,2) > (1,4))
"""
依次从前到后比较
返回 True
"""
from random import randint
#第一种方法
d = {k:randint(60,100) for k in 'abcdefg'}
# print(d)
l = [(v,k) for k ,v in d.items()]
# print(l)
l = sorted(l,reverse=True)
# print(l)
"""
True
{'a': 87, 'b': 89, 'c': 86, 'd': 60, 'e': 99, 'f': 77, 'g': 87}
[(87, 'a'), (89, 'b'), (86, 'c'), (60, 'd'), (99, 'e'), (77, 'f'), (87, 'g')]
[(99, 'e'), (89, 'b'), (87, 'g'), (87, 'a'), (86, 'c'), (77, 'f'), (60, 'd')]
"""
#第二种
d = {k:randint(60,100) for k in 'abcdefg'}
# print(d)
l = list(zip(d.values(),d.keys()))
# print(l)
l = sorted(l,reverse=True)
# print(l)
"""
True
{'a': 72, 'b': 92, 'c': 85, 'd': 65, 'e': 75, 'f': 69, 'g': 62}
[(72, 'a'), (92, 'b'), (85, 'c'), (65, 'd'), (75, 'e'), (69, 'f'), (62, 'g')]
[(92, 'b'), (85, 'c'), (75, 'e'), (72, 'a'), (69, 'f'), (65, 'd'), (62, 'g')]
"""
#第三种
d = {k:randint(60,100) for k in 'abcdefg'}
print(d.items())
l=sorted(d.items(),key=lambda item:item[1],reverse=True)
print(l)
p = list(enumerate(l,1))
print(p)
t={}
for i ,(k,v) in p:
print(i,k,v)
t[k] = (i,v)
print(t)
"""
True
dict_items([('a', 96), ('b', 85), ('c', 85), ('d', 71), ('e', 87), ('f', 98), ('g', 82)])
[('f', 98), ('a', 96), ('e', 87), ('b', 85), ('c', 85), ('g', 82), ('d', 71)]
[(1, ('d', 95)), (2, ('a', 93)), (3, ('f', 93)), (4, ('c', 91)), (5, ('b', 67)), (6, ('e', 67)), (7, ('g', 62))]
1 d 100
2 c 94
3 a 88
4 b 80
5 g 73
6 f 70
7 e 68
{'a': (1, 98), 'g': (2, 90), 'f': (3, 84), 'e': (4, 80), 'd': (5, 66), 'c': (6, 65), 'b': (7, 60)}
"""
View Code
05如何统计序列中元素的频度
from random import randint#随机生成一个列表 有重复的数字
data = [randint(0,20) for _ in range(30)]
print(data)
#[16, 3, 6, 0, 4, 20, 1, 0, 13, 16, 13, 6, 14, 13, 16, 4, 14, 9, 12, 5, 4, 6, 1, 7, 18, 5, 6, 15, 14, 5]
#列表每个元素作为键,值默认为0(出现个数)
d= dict.fromkeys(data,0)
print(d)
#{16: 0, 3: 0, 6: 0, 0: 0, 4: 0, 20: 0, 1: 0, 13: 0, 14: 0, 9: 0, 12: 0, 5: 0, 7: 0, 18: 0, 15: 0}
#迭代列表 遇到某个数值就+1 统计数字出现个数
for x in data:
d[x] += 1
print(d)
#{16: 3, 3: 1, 6: 4, 0: 2, 4: 3, 20: 1, 1: 2, 13: 3, 14: 3, 9: 1, 12: 1, 5: 3, 7: 1, 18: 1, 15: 1}
p = sorted([(v,k) for k,v in d.items()],reverse=True)
print(p)
#[(5, 19), (2, 17), (2, 16), (2, 12), (2, 8), (2, 6), (2, 4), (2, 3), (2, 1), (2, 0), (1, 20), (1, 15), (1, 14), (1, 10), (1, 9), (1, 7), (1, 2)]
05.1 collection 统计频率
from random import randintfrom collections import Counter
#随机生成一个列表 有重复的数字
data = [randint(0,20) for _ in range(30)]
# print(data)
p = Counter(data)
l=p.most_common(3)
print(p)
print(l)
Counter({4: 4, 11: 3, 6: 3, 7: 3, 3: 2, 17: 2, 9: 2, 20: 2, 0: 2, 10: 1, 16: 1, 2: 1, 13: 1, 15: 1, 12: 1, 18: 1})
[(4, 4), (11, 3), (6, 3)]
6,如何快速找到多个字典中的公共键key
第一种:
# print(sample('abcdefgh',3))
#['g', 'e', 'b'] 随机
d1={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
# print(d1)
#随机返回3-6名球员 和 进球数
#{'d': 2, 'f': 1, 'e': 1, 'g': 3, 'c': 3, 'b': 2}
d2={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
d3={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
dl = [d1,d2,d3]
#3轮都有进球的球员
print( [k for k in dl[0] if all(map(lambda d:k in d,dl[1:]))])
#解释
#map(lambda d:k in d,dl[1:]) 和PHP的array_map一样的作用
#判断k 是否在d2,d3中 all()表示全在
第二种方法:
from random import randint,samplefrom functools import reduce
# print(sample('abcdefgh',3))
#['g', 'e', 'b'] 随机
d1={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
# print(d1)
#随机返回3-6名球员 和 进球数
#{'d': 2, 'f': 1, 'e': 1, 'g': 3, 'c': 3, 'b': 2}
d2={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
d3={k:randint(1,4) for k in sample('abcdefgh',randint(3,6)) }
dl = [d1,d2,d3]
#3轮都有进球的球员
print(d1.keys())
print(dict.keys(d1))
d = map(dict.keys,dl)
dd = reduce(lambda a,b:a & b,map(dict.keys,dl))
print(dd)
dict_keys(['f', 'b', 'a', 'c', 'e', 'd'])
dict_keys(['f', 'b', 'a', 'c', 'e', 'd'])
{'f', 'd', 'a', 'b'}
7,如何让字典保持有序
from random import shuffle
from itertools import islice
od = OrderedDict()
od['c'] = 1
od['b'] = 2
od['a'] = 3
print(od.keys())
players = list('abcdefgh')
shuffle(players)
print(players)
od = OrderedDict()
for i,p in enumerate(players,1):
od[p] = i
print(od)
def queryByOrder(d,a,b=None):
a -= 1
if b is None:
b = a+1
return list(islice(od,a,b))
print(queryByOrder(od,2,4))
odict_keys(['c', 'b', 'a'])
['c', 'd', 'a', 'e', 'b', 'g', 'f', 'h']
OrderedDict([('c', 1), ('d', 2), ('a', 3), ('e', 4), ('b', 5), ('g', 6), ('f', 7), ('h', 8)])
['d', 'a', 'e']
8,如何实现用户历史记录功能
from random import randintdef guess(n,k):
if n == k:
print('猜对了,这个数字是%d.' % k)
return True;
if n < k:
print('猜大了,比%d小.' % k)
elif n > k:
print('猜小了,比%d大.' % k)
return False
def main():
n = randint(1,100)
i = 1
while True:
line = input('[%d] 请输入一个数字:' % i)
if line.isdigit():
k = int(line)
i += 1
if guess(n,k):
break
elif line == 'quit':
break
if __name__ == '__main__':
main()
猜小了,比24大.
[2] 请输入一个数字:56
猜小了,比56大.
[3] 请输入一个数字:4
猜小了,比4大.
[4] 请输入一个数字:
from collections import deque
q = deque([],5)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
print(q)
q.append(6)
print(q)
deque([1, 2, 3, 4, 5], maxlen=5)
deque([2, 3, 4, 5, 6], maxlen=5)
2 from collections import deque
3 def guess(n,k):
4 if n == k:
5 print('猜对了,这个数字是%d.' % k)
6 return True;
7 if n < k:
8 print('猜大了,比%d小.' % k)
9 elif n > k:
10 print('猜小了,比%d大.' % k)
11
12 return False
13
14 def main():
15 n = randint(1,100)
16 i = 1
17 hq = deque([],5)
18 while True:
19 line = input('[%d] 请输入一个数字:' % i)
20 if line.isdigit():
21 k = int(line)
22 hq.append(k)
23 i += 1
24 if guess(n,k):
25 break
26 elif line == 'quit':
27 break
28 elif line == 'h?':
29 print(list(hq))
30
31 if __name__ == '__main__':
32 main()
改良版增加deque
pickle模块:from collections import dequeimport pickle
q = deque([],5)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
print(q)
q.append(6)
print(q)
# pickle.dump(q,open('save.pkl','wb'))
b = pickle.load(open('save.pkl','rb'))
print(b)
deque([1, 2, 3, 4, 5], maxlen=5)
deque([2, 3, 4, 5, 6], maxlen=5)
deque([2, 3, 4, 5, 6], maxlen=5)
pickle
pickle保存文件格式
�ccollectionsdeque
q )K�qRq(KKKKKe.