Python--强化--Day01
🧸如何在列表,字典,集合中根据条件筛选数据?
🎈题目1:列表解析–过滤列表中部的负数
import timeit
from random import randint
data = [randint(-10, 10) for _ in range(10)]
print(data)
r = filter(lambda x: x >= 0, data)
print(list(r))
r2 = [x for x in data if x >= 0]
print(r2)
print(timeit.timeit("filter(lambda x: x >= 0, data)", 'from __main__ import data'))
print(timeit.timeit("[x for x in data if x >= 0]", 'from __main__ import data'))
🎈题目2:字典解析–过滤列表学生成绩大于90的
from random import randint
student_id_and_score = {x: randint(60, 100) for x in range(20200001, 20200021)}
print(student_id_and_score)
r = {k: v for k, v in student_id_and_score.items() if v > 90}
print(r)
🎈集合解析:
from random import randint
data = [randint(0, 20) for _ in range(10)]
s = set(data)
print(s)
r = {x for x in s if x % 3 == 0}
print(r)
🧸如何为元祖中的每个元素命名,提高程序的可读性?
NAME, AGE, SEX, EMAIL = range(4)
student = ('Jim', 16, 'male', 'jim123@gmail.com')
print(student[0])
print(student[NAME])
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s = Student('Jim', 16, 'male', 'jim123@gmail.com')
print(s.name)
print(isinstance(s, tuple))
🧸如何统计序列中元素出现的频度?
from random import randint
from collections import Counter
import re
data = [randint(0, 20) for _ in range(30)]
print(data)
c = dict.fromkeys(data, 0)
for i in data:
c[i] += 1
print(c)
c2 = Counter(data)
print(c2)
print(c2.most_common(3))
f = open(r'D:\test.txt', encoding='utf-8').read()
c3 = Counter(re.split('\W+', f))
print(c3)
print(c3.most_common(5))
🧸如何根据字典中值得大小,对字典中的项排序?
from random import randint
stu_score = {x: randint(60, 100) for x in 'xyzabc'}
print(stu_score)
print(sorted(stu_score))
print(stu_score.keys())
print(stu_score.values())
z = zip(stu_score.values(), stu_score.keys())
z1 = list(z)
print(sorted(z1))
print(stu_score.items())
z2 = sorted(stu_score.items(), key=lambda x: x[1])
print(z2)
🧸如何快速找到多个字典的公共健(key)?
from functools import reduce
from random import randint, sample
print(sample('abcdefg', 3))
s1 = {i: randint(1, 4) for i in sample('abcdefg', randint(3, 6))}
s2 = {i: randint(1, 4) for i in sample('abcdefg', randint(3, 6))}
s3 = {i: randint(1, 4) for i in sample('abcdefg', randint(3, 6))}
print(s1)
print(s2)
print(s3)
r = []
for k in s1:
if k in s2 and k in s3:
r.append(k)
print(r)
r2 = s1.keys() & s2.keys() & s3.keys()
print(list(r2))
rm = map(dict.keys, [s1, s2, s3])
print(list(rm))
r3 = reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3]))
print(r3)
🧸如何让字典保持有序?
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5jYg3zcw-1653276902215)(https://raw.githubusercontent.com/kurry0123/Py-learn-imgs/main/img/202205231134740.png)]
d = {}
d['Jim'] = (1, 35)
d['Leo'] = (2, 45)
d['Bob'] = (3, 50)
for i in d: print(i)
from collections import OrderedDict
d2 = OrderedDict()
d2['Jim'] = (1, 35)
d2['Leo'] = (2, 45)
d2['Bob'] = (3, 50)
for i in d2: print(i)
from time import time
from random import randint
from collections import OrderedDict
players = list('ABCDEFGH')
stat_time = time()
l = len(players)
d = OrderedDict()
for i in range(l):
print('请输入,完成提交:')
input()
p = players.pop(randint(0, l-1 - i))
end_time = time()
sum_time = end_time - stat_time
print(i + 1, p, sum_time)
d[p] = (i+1, sum_time)
print('='*20)
for k in d:
print(k, d[k])
🧸如何实现用户的历史记录功能:
🎈pickle的使用:
import pickle
from collections import deque
q = deque([[20, 10, 50, 60, 70]])
print(q)
pickle.dump(q, open('history_demo', 'wb'))
q2 = pickle.load(open('history_demo', 'rb'))
print(q2)
数字游戏实例:
from random import randint
from collections import deque
import pickle
N = randint(0, 100)
history = deque([], 5)
def guss(k):
if k == N:
print('Right')
return True
if k < N:
print('%s is less-than N' %k)
else:
print('%s is greater-than N'%k)
return False
while True:
line = input('Please input a number:')
if line.isdigit():
k = int(line)
history.append(k)
pickle.dump(history, open('history', 'wb'))
if guss(k):
break
elif line == 'history' or 'h?':
print(list(history))
print(pickle.load(open('history', 'rb')))
|