student = {'name': 'zhangxiaohua', 'age': 22, 'score': 99, 'tel': '123456', 'gender': 'boy'}
six_students = [{'name': '小花', 'age': 22, 'score': 99, 'tel': '123456', 'gender': '男'},{'name': '张三', 'age': 25, 'score': 53, 'tel': '133466', 'gender': '男'},{'name': '李四', 'age': 18, 'score': 89, 'tel': '122455', 'gender': '女'},{'name': '康康', 'age': 19, 'score': 36, 'tel': '789456', 'gender': '男'},{'name': '丽萨', 'age': 24, 'score': 68, 'tel': '499568', 'gender': '女'},{'name': '小明', 'age': 22, 'score': 92, 'tel': '199363', 'gender': '不明'}
]
count = 0
for x in six_students:if x['score'] < 60:count += 1
print(count)
for x in six_students:if x['score'] < 60 and x['age'] < 18:print(x['name'], x['score'])
total_age = 0
count = 0
for x in six_students:if x['gender'] == 男:total_age += x['age']count += 1
print(total_age/count)
for x in six_students:if x['tel'][-1] == '8':print(x['name'])
for x in six_students:if x['gender'] == '不明':x.clear()
print(six_students)
7. 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)
class1 = {'name': 'python2301','location': '21教','lecturer': {'name': '余婷','age': 18,'gender': 'woman','tel': '1008611'},'headTeacher': {'name': '萍姐','age': 18,'tel': '10010'},'all_students': [{'name': 'xiaohua', 'age': 22, 'tel': '1362824', 'major': '计科','score': 100, 'linkman': {'name': 'zhang', 'tel': '1993638'}},{'name': 'xiaoming', 'age': 30, 'tel': '1362825', 'major': '计科','score': 95, 'linkman': {'name': 'li', 'tel': '1990310'}},{'name': 'stu4', 'age': 16, 'tel': '827222', 'major': '数学','score': 99, 'linkman': {'name': '王五', 'tel': '8628101'}}]
}
已知一个列表保存了多个狗对应的字典:
dogs = [{'name': '贝贝', 'color': '白色', 'breed': '银狐', 'age': 3, 'gender': '母'},{'name': '花花', 'color': '灰色', 'breed': '法斗', 'age': 2},{'name': '财财', 'color': '黑色', 'breed': '土狗', 'age': 5, 'gender': '公'},{'name': '包子', 'color': '黄色', 'breed': '哈士奇', 'age': 1},{'name': '可乐', 'color': '白色', 'breed': '银狐', 'age': 2},{'name': '旺财', 'color': '黄色', 'breed': '土狗', 'age': 2, 'gender': '母'}
]
利用列表推导式获取所有狗的品种
[‘银狐’, ‘法斗’, ‘土狗’, ‘哈士奇’, ‘银狐’, ‘土狗’]
result = [x['breed'] for x in dogs]
print(result)
利用列表推导式获取所有白色狗的名字
[‘贝贝’, ‘可乐’]
result = [x['name'] for x in dogs if x['color'] == '白色']
print(result) # ['贝贝', '可乐']
给dogs中没有性别的狗添加性别为 ‘公’
for x in dogs:x.setdefault('gender', '公')
print(dogs)
统计 ‘银狐’ 的数量
count = 0
for x in dogs:if x['breed'] == '银狐':count += 1
print(count) # 2