字典练习题

Posted h1227

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典练习题相关的知识,希望对你有一定的参考价值。

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

# l = [11,22,33,44,55,66,77,88,99,90]
# dict = {‘k1‘:[], ‘k2‘:[]}
# for i in l:
# if i > 66:
# dict[‘k1‘].append(i)
# if i < 66:
# dict[‘k2‘].append(i)
# print(dict)

# 2 统计s=‘hello alex alex say hello sb sb‘中每个单词的个数
# 结果如:{‘hello‘: 2, ‘alex‘: 2, ‘say‘: 1, ‘sb‘: 2}
# 方法一
# dict = {}
# s = ‘hello alex alex say hello sb sb‘
# l = s.split()
# for i in l:
# if i in dict:
# dict[i] += 1
# else:
# dict[i] = 1
# print(dict)

# 方法二
# s=‘hello alex alex say hello sb sb‘
# # dic={}
# # words=s.split()
# # # print(words)
# # for word in words: #word=‘alex‘
# # dic[word]=s.count(word) # count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
# # print(dic)

# 方法三
# setdefault() 方法和 get()方法 类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。
# s=‘hello alex alex say hello sb sb‘
# dic = {}
# l = s.split()
# for i in l:
# dic.setdefault(i,s.count(i))
# print(dic)

# 方法四
# set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
# s=‘hello alex alex say hello sb sb‘
# dic = {}
# l = s.split()
# # print(set(l))
# for i in set(l):
# dic[i] = s.count(i)
# print(dic)

以上是关于字典练习题的主要内容,如果未能解决你的问题,请参考以下文章

练习题2:添加字典节点

字典练习题

字典练习题

列表,元组,字典,集合 练习题

字符串练习题:拼接最小字典序

js字典的两道练习题