携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天
- NP71 喜欢的颜色
描述
驼瑞驰调查了班上部分同学喜欢哪些颜色,并创建了一个依次包含键-值对'Allen': ['red', 'blue', 'yellow']、'Tom': ['green', 'white', 'blue']和'Andy': ['black', 'pink']的字典result_dict,作为已记录的调查结果。
现在驼瑞驰想查看字典result_dict的内容,你能帮帮他吗?
使用for循环遍历"使用sorted()函数按升序进行临时排序的包含字典result_dict的所有键的列表",对于每一个遍历到的名字,先使用print()语句一行输出类似字符串"Allen's favorite colors are:"的语句,然后再使用for循环遍历该名字在字典result_dict中对应的列表,依次输出该列表中的颜色。
输入描述:
无
输出描述:
按题目描述进行输出即可。
Allen's favorite colors are:
red
blue
yellow
Andy's favorite colors are:
black
pink
Tom's favorite colors are:
green
white
blue
参考代码如下:
result_dict = {'Allen': ['red', 'blue', 'yellow'],'Tom': ['green', 'white', 'blue'],'Andy': ['black', 'pink']}
for i in sorted(result_dict.keys()):
print("%s's favorite colors are: "%i)
for x in result_dict[i]:
print(x)
- NP72 生成字典
描述
牛牛有两份列表,一份记录了牛客网用户的名字,另一份记录他们使用的语言。假设两份列表一一对应,请使用zip函数将两份列表封装为字典,以名字为key,语言为value,然后直接输出字典。
输入描述:
第一行输入多个字符串表示用户名字,以空格间隔。
第二行输入多个字符串表示使用的语言,以空格间隔。
输出描述:
直接输出两个列表组成的字典。
示例1
参考代码如下:
key = input().split()
value = input().split()
print(dict(zip(key,value)))
zip函数的原型为:zip([iterable, …]) 参数iterable为可迭代的对象,并且可以有多个参数。该函数返回一个以[元组]
(为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。
返回的列表长度被截断为最短的参数序列的长度。
- NP73 查字典
描述
正在学习英语的牛妹笔记本上准备了这样一个字典:{'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}。
请你创建这样一个字典,对于牛妹输入的字母,查询有哪些单词?
输入描述:
输入一个字母,必定在上述字典中。
输出描述:
同一行中依次输出每个单词,单词之间以空格间隔。
示例1
参考代码如下:
dict1 = {'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
x = input()
for i in dict1.get(x): # for i in dict1[x]:
print(i,end=' ')
print(dict1.get(x))的值是['apple', 'abandon', 'ant'] 同样道理:在for循环里,i的值依次是在value的列表里。所以也就是打印要输出的值 dict1[x] === dict1.get(x)
- NP74 字典新增
描述
正在学习英语的牛妹创建了一个字典:{'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}。现牛妹新学了一个字母letter,以及一个新单词word,请把它们增加到字典中,再输出更新后的字典。
输入描述:
第一行输入一个新字母letter,
第二行输入一个新单词word。
输出描述:
输出更新后的整个字典。
示例1
参考代码:
dict_1 = {'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
letter = input()
word = input()
dict_1[letter] = word
print(dict_1)
- NP75 使用字典计数
描述
Python的字典可以用来计数,让要被计数的元素作为key值,它出现的频次作为value值,只要在遇到key值后更新它对应的value即可。现输入一个单词,使用字典统计该单词中各个字母出现的频次。
输入描述:
输入一个字符串表示单词,只有大小写字母。
输出描述:
直接输出统计频次的字典。
我的代码如下:
w = input()
dict_1 = {}
#在字符串的每一个字符之间插入一个空格组成一个新的字符串
#w= ' '.join(w)
#w_1 = w.split(" ") #即将字符串分割开来
for i in w:
num = w.count(i)
dict_1[i] = num
print(dict_1)
参考别人的代码:[个人觉得这个代码很不错,比较明白]
# 1.获取用户输入;
x = input()
# 2.创建两个空列表;
y = []
c = []
# 3.遍历用户输入的字符串,并将其逐一添加至空列表y中;
for i in x:
y.append(i)
# 4.遍历列表y,先数一下列表y中有几个参数,然后将其添加至空列表c中;
for a in y:
c.append(y.count(a))
# 5.先将两个列表打包,然后创建字典,然后将其输出
print(dict(zip(y, c)))
关于count函数:
-
string 中 某字符 的次数
str.count(sub, start= 0,end=len(string))
-
list 中 某元素 的次数
list.count(obj)