完成以下操作:(1)向每条记录中添加新键值”gender”,第1和第3人为”male”,第2人为”female”。(2)打印“高小二”的薪资;(3)打印所有人的薪资;(4)打印表中所有人的全部信息;(5)按性别求平均薪资并输出。代码注释
时间: 2024-05-20 13:17:49 浏览: 28
# 定义表格
table = [
{"name": "张三", "age": 18, "salary": 3000},
{"name": "李四", "age": 20, "salary": 3500},
{"name": "王五", "age": 22, "salary": 4000}
]
# 添加新键值"gender"
table[0]["gender"] = "male"
table[1]["gender"] = "female"
table[2]["gender"] = "male"
# 打印“高小二”的薪资
for person in table:
if person["name"] == "高小二":
print(person["salary"])
# 打印所有人的薪资
for person in table:
print(person["salary"])
# 打印表中所有人的全部信息
for person in table:
print(person)
# 按性别求平均薪资并输出
male_salary = 0
male_count = 0
female_salary = 0
female_count = 0
for person in table:
if person["gender"] == "male":
male_salary += person["salary"]
male_count += 1
elif person["gender"] == "female":
female_salary += person["salary"]
female_count += 1
if male_count > 0:
print("Male average salary:", male_salary/male_count)
if female_count > 0:
print("Female average salary:", female_salary/female_count)
阅读全文