字典练习2答案

练习2:统计s='hello alex alex say hello sb sb'中每个单词的个数。结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}

# 答案1:
s='hello alex alex say hello sb sb'
words = s.split()
results = {}
for i in words:
    results[i] = s.count(i)
    print(results)


# 答案2:
s='hello alex alex say hello sb sb'
words = s.split()
results = {}
for i in words:
    results.setdefault(i, s.count(i))
    print(results)

    
# 答案3:
s='hello alex alex say hello sb sb'
words = s.split()
results = dict.fromkeys(words, 0)
for key in words:
    results[key] += 1
    print(results)
posted @ 2020-02-27 20:56  the3times  阅读(210)  评论(0编辑  收藏  举报