解题方法
方法1
# 创建fruit number列表, 分别表示牛客水果店各种水果的数量
fruit = ['apple', 'banana', 'strawberry', 'orange', 'mango', 'grape', 'blueberry']
number = [1, 3, 5, 6, 13, 21, 10]
# 创建字典 fruit_dict
fruit_dict = dict()
# 将fruit和number列表,组成字典
for i in range(len(fruit)):
fruit_dict[fruit[i]] = number[i]
# 在字典中根据输入水果品种查询该水果的数量
str = str(input())
if str in fruit:
print(fruit_dict[str])
# 如果输入不属于字典中的水果,则输出0
else:
print(0)
方法2:
# 创建fruit number列表, 分别表示牛客水果店各种水果的数量
fruit = ['apple', 'banana', 'strawberry', 'orange', 'mango', 'grape', 'blueberry']
number = [1, 3, 5, 6, 13, 21, 10]
# 映射函数方式来构造字典 fruit_dict
fruit_dict = dict(zip(fruit, number))
# 在字典中根据输入水果品种查询该水果的数量(如果输入不属于字典中的水果,则输出0)
print(fruit_dict.get(str(input()),0))
收获
收获1:zip函数
# zip(fruit,number)的结果: [('apple', 1), ('banana', 3), ('strawberry', 5), ....]
收获2:dict()创建字典
# 1. 创建空字典:
① a = dict()
② a = {}
# 2.传入关键字
① a = dict(a='c', b='d', t='e')
② a = {'a': 'c', 'b': 'd', 't': 'e'}
③ a = {}
a['a'] = 'c'
a['b'] = 'd'
a['t'] = 'e'
# 3. 映射函数方式来构造字典:dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> {'three': 3, 'two': 2, 'one': 1}
# 4.可迭代对象方式来构造字典(key在前,value在后):dict([('one', 1), ('two', 2), ('three', 3)])
>>> {'three': 3, 'two': 2, 'one': 1}
收获3:dict.get(key, default=None)
dict.get(key, default=None)
- key -- 要查找的键
- default -- 如果指定键的值不存在,返回该默认值