大爽Python入门教程 2-5 习题答案

大爽Python入门公开课教案 点击查看教程总目录

1 基础打招呼

参考答案

names = "Alan, Bruce, Carlos, David, Emma"
name_list = names.split(",")
for name in name_list:
    name = name.strip()
    print("Hello, %s!" % name)

2 逐个介绍

参考答案

infos = [
    "Alan, 19",
    "Bruce, 22",
    "Carlos, 23",
    "David, 18",
    "Emma, 21"
]

for info in infos:
    name, age = info.split(",")
    age = age.strip()
    print("I am %s. I'm %s years old." % (name, age))

3 列表改成字典

参考答案

info_list = [
    ("Alan", 90),
    ("Bruce", 80),
    ("Carlos", 85),
    ("David", 92),
    ("Emma", 81),
]

info_dict = {}

for item in info_list:
    name, age = item
    info_dict[name] = age

print(info_dict)

4 列表使用

参考答案

info = ["zhang san", 30, "programmer", 7]

print("I am %s, %s years old. I work as a %s for %s years." % (info[0], info[1], info[2], info[3]))

5 汇总求和

参考答案

shop_cart = [
    ("apple", 20),
    ("banana", 20),
    ("cherry", 15),
    ("apple", 30),
    ("banana", 10),
    ("banana", 25),
]

shop_dict = {}
for item in shop_cart:
    name, weight = item
    if name not in shop_dict:
        shop_dict[name] = weight
    else:
        shop_dict[name] += weight

for name in shop_dict:
    weight = shop_dict[name]
    print("%s: %s"% (name, weight))
posted @ 2021-09-12 21:19  大爽歌python编程辅导  阅读(70)  评论(0编辑  收藏  举报