先处理下两道作业题:(完全不会做的题)
例题一:
.定义一个学生类。该类的属性如下:
-姓名 字符串
年龄 整型
-成绩(语文,数学,英语)字典,科目名称为键,成绩为值
该类的方法:
-获取学生的姓名: get_ _name() 返回类型:str
-获取学生的年龄: get_ age() 返回类型:int
-返回3门科目中最高分数的课程。get_ course()
-返回该学生的平均成绩get_ avg()
解答:
类的属性 是 字典,该怎么实例化呢?:
def __init__(self,name,age,score={"language": 0, "english": 0, "math": 0}):
self.name = name
self.age = age
self.score=score
stu1 = Student("王",18,score={"language":60,"english":70,"math":100})
如何获取最高分学科:看代码啊
def get_Course(self):
max_score = 0
max_course = None
for key, value in self.score.items():
if value >= max_score:
max_score = value
max_course = key
return max_course
格式化输出保留两位小数:
“{:.2f}”.format
print("{:.2f}".format(stu1.get_avg()))
所有代码:
class Student:
def __init__(self, name, age, score={"language": 0, "english": 0, "math": 0}):
self.name = name
self.age = age
self.score = score
def get_name(self):
return self.name
def get_age(self):
return self.age
def get_Course(self):
max_score = 0
max_course = None
for key, value in self.score.items():
if value >= max_score:
max_score = value
max_course = key
return max_course
def get_avg(self):
return sum(self.score.values()) / (len(self.score))
stu1 = Student("王", 18, score={"language": 60, "english": 70, "math": 100})
print(stu1.get_Course())
print("{:.2f}".format(stu1.get_avg()))
例题二:
写一个游戏机器人自动游戏比赛,定义一个类:AutoRobot,
类中存在一个全局类 成员gameDic = [‘石头’,‘剪刀’,‘布’],
然后需要定义一个分数值 Score记录比赛分数。 谁赢谁加1分,打平双方不加分。
比赛规则为 石头>剪刀>布>石头 然后定义一个play方法让两个机器人出拳,
可以指定比赛局数。 完成两个机器人之间的比赛!
前提知识:
@classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。
如何使程序 随机生成一个列表中的值:
gameDic = ['剪刀','石头','布']
random.choice(cls.gameDic)
如何判断剪刀石头布的输赢?
把剪刀石头布的下标进行运算
def adjudge(self,choices1,choices2):
'''
对自己和对方的选择进行比较,如果自己赢了就加一分
:param choices1: 自己出的
:param choices2: 对方出的
:return:
'''
ch1_index = self.gameDic.index(choices1) #返回的是下标
ch2_index = self.gameDic.index(choices2) #返回的是下标
cmp = ch1_index - ch2_index
if cmp == 1 or cmp == -2:
self.score += 1
所有代码:
import random
class AutoRobot:
gameDic = ['剪刀','石头','布']
def __init__(self):
self.score = 0
@classmethod
def play(cls):
'''
随机返回剪刀石头布
:return:
'''
return random.choice(cls.gameDic)
def adjudge(self,choices1,choices2):
'''
对自己和对方的选择进行比较,如果自己赢了就加一分
:param choices1: 自己出的
:param choices2: 对方出的
:return:
'''
ch1_index = self.gameDic.index(choices1) #返回的是下标
ch2_index = self.gameDic.index(choices2) #返回的是下标
cmp = ch1_index - ch2_index
if cmp == 1 or cmp == -2:
self.score += 1
if __name__ =='__main__':
robot1 = AutoRobot()
robot2 = AutoRobot()
for i in range(50):
ch1 = robot1.play()
ch2 = robot2.play()
robot1.adjudge(ch1,ch2)
robot2.adjudge(ch2,ch1)
print(robot1.score)
print(robot2.score)
文件读写
读文件:
写法一:直接open ,但需要 关闭file
file = open("../news",mode='r',encoding="utf-8")
print(file.readline()) #读指定字节大小数据
print(file.read(10)) #读指定大小的数据
print(file.readlines()) #读所有行,返回一个列表
file.close()
写法二:with语句
with 语句 + open + as
with 语句可以配合资源管理器来使用,可以自动释放资源,不需要关闭 ,它自动关闭
file = open("../news",mode='r',encoding="utf-8")
with open("../news",mode='r',encoding="utf-8") as file :
print(file.read())
写入文件:
文件内容写入
写入文件
with open("../news",mode='w',encoding="utf-8") as file:
file.write("我是sssssssss")
中午的作业题:
- 请将 python之禅 zen.txt 里面长度大于等于 4 的单词(不用处理标点符号,但要处理换行符),首尾各取 2 个字母组合成一个新的单词,并将这个单词添加到一个列表里面,打印出来
核心代码:首尾各取两个字母
new_words.append(word[:2] + word[-2:])
with open("zen.txt",mode="r",encoding="utf-8") as f:
content = f.read()
content.replace(".\n"," ")
words = content.split(" ")
newwords = []
for word in words:
if len(word) >= 4:
newwords.append(word[:2] + word[-2:])
- 编写一个简单的注册函数。
要求用户输入用户名和密码,如果用户名为空或密码长度小于6位则提示用户错误信息后返回。
如果用户输入正确,则提示用户注册成功,并将该用户信息保存到本地文件中。
要求保存时加入一个从 0 开始的整数 id 值,每个用户的 id 值依次递增 1。
再次运行程序时,可以从已有的用户id值继续往下添加。
核心思想:如何将dict对象转化成 json字符串,如何把json字符串转化成dict对象
json.loads("json字符串") # 把 json 字符串解析为 python 字典 dict
json.dumps(dict对象) # 把 dict 对象转换为一个 json 字符串
将txt文件里的json字符串转化成字典格式
if os.path.exists("users"):
with open("users", mode="r", encoding="utf-8") as f:
users = f.read()
users = json.loads(users)
把字典类型的用户数据转换为 json 字符串后,写入文件中
def save_user_infos(users):
"""
把字典类型的用户数据转换为 json 字符串后,写入文件中
:param users:
:return:
"""
with open("users", mode="w", encoding="utf-8") as f:
f.write(json.dumps(users))
import json
import os
def read_user_infos() -> dict:
"""
从文件中读取用户信息数据
:return: 返回一个字典 {0:['zhangsan','123456'], 1:['lisi','abcd5678']}
"""
if os.path.exists("users"):
with open("users", mode="r", encoding="utf-8") as f:
users = f.read()
users = json.loads(users)
else:
users = {}
return users
def save_user_infos(users):
"""
把字典类型的用户数据转换为 json 字符串后,写入文件中
:param users:
:return:
"""
with open("users", mode="w", encoding="utf-8") as f:
f.write(json.dumps(users))
def register():
"""
1. 接受用户的输入,输入用户名和密码
2. 检查用户的输入,用户名不能为空,密码长度不能小于6位,如果不满足条件提示用户
3.1 读取文件中已经存储的用户数据到内存中,并且解析 json 字符串为对象
3.2 保存用户名和密码,保持到内存中
4. 程序退出的时候,保持用户信息到文件中,把内存中对象数据转换为 json 字符串,存储到文件
:return:
"""
checked = False
while not checked:
# 1.接受用户的输入,输入用户名和密码
username = input("请输入用户名")
password = input("请输入密码")
# 2. 检查用户的输入,用户名不能为空,密码长度不能小于6位,如果不满足条件提示用户
if all([username, password]) and len(password) >= 6:
checked = True
elif username.strip() == "":
print("用户名不能为空")
elif len(password) < 6:
print("密码长度不能小于6位")
users = read_user_infos()
max_key = -1
for key in users.keys():
if max_key < int(key):
max_key = int(key)
users[str(max_key+1)] = [username, password]
save_user_infos(users)
if __name__ == '__main__':
register()
高阶函数
map
1.计算列表中元素的平方
l = [2, 8, 10, 20, 3, 9, 8]
print(list(map(lambda x: x ** 2, l)))
2.提供了两个列表,对相同位置的列表数据进行相加
比如:[1, 3, 5, 7, 9], [2, 4, 6, 8, 10],结果为 [3, 7, 11, 15, 19]
y = 3*x1 + 4*x2 + 8*x3 +1
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8, 10]
m = map((lambda x1, x2: x1 + x2), l1, l2)
print(list(m))
for item in m:
print(item)
filter
1.过滤出列表中的所有奇数
l = [1, 4, 56, 23, 44, 6, 8, 9, 10, 14, 18, 13, 21]
def is_odd_number(num):
return num % 2 != 0
print(list(filter(is_odd_number, l)))
reduce
需要引入包functools
import functools
l = [1, 2, 3, 4, 5]
print(functools.reduce(lambda acc, x: acc + x, l))