Python高手之路体验课 第 16 / 18 篇

数据类型-字典集合与布尔类型-参考答案

作业一

有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中,即: {‘k1’: 大于66的所有值, ‘k2’: 小于66的所有值}

demo_set = {11, 22, 33, 44, 55, 66, 77, 88, 99, 90}

res_dict = {'k1': [], 'k2': []}

for i in demo_set:
    if i > 66:
        res_dict['k1'].append(i)
    elif i < 66:
        res_dict['k2'].append(i)

print(res_dict)

作业二

使用至少两种方法统计字符串 s=‘hello albert albert say hello world world’中每个单词的个数,结果如:

{'hello': 2, 'albert': 2, 'say': 1, 'world': 2}
# 方式一
s = 'hello albert albert say hello world world'

list1 = s.split()
print(list1)
dict1 = {}
for i in list1:
    if i not in dict1:
        dict1[i] = 1
    else:
        dict1[i] += 1

print(dict1)

# 方式二
dict2 = {}
words = s.split()
for word in words:
    dict2[word] = s.count(word)

print(dict2)

作业三

实现简易购物程序,要求如下:首先打印商品详细信息,然后请用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入

msg_dic = {
    'apple': 10,
    'tesla': 1000000,
    'mac': 10000,
    'iphone': 8000,
    'chicken': 30,
    'pen': 3,
    'ruler': 5
}
msg_dic = {
    'apple': 10,
    'tesla': 1000000,
    'mac': 10000,
    'iphone': 8000,
    'chicken': 30,
    'pen': 3,
    'ruler': 5
}
goods_list = []
while True:
    for product, price in msg_dic.items():
        print('product: %s, price: %s' % (product, price))
    choice = input('please choose product>>:').strip()
    if choice == 'q':  # user can quit the program by inputting 'q'
        break
    elif choice not in msg_dic:
        print('The product you choose is invalid')
        continue
    else:
        while True:
            count = input('please input the number of the product>>:').strip()
            if not count.isdigit():
                print('The content you input is not number')
                continue
            else:
                goods_list.append((choice, msg_dic[choice], count))
                print(goods_list)
                break

解题思路参考:

image.png