【发布时间】:2017-12-06 22:11:48
【问题描述】:
我认为我对如何解决此功能有正确的想法,但我不确定 为什么我没有得到文档字符串中显示的所需结果。谁能帮我解决这个问题?
def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
count = count + length
d[length] = {count}
count += 1
return d
【问题讨论】:
-
d[length] = {count}绝对不是你想要的。 -
为什么不呢?长度是键,频率是计数,是值。
-
不,长度是key,value是一个
set,包含一个元素,是一个int,代表频率。
标签: python python-3.x