我认为我对如何解决这个功能有正确的想法,但我不确定 为什么我没有得到文档字符串中显示的所需结果。有人可以帮我解决这个问题吗?
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
答案 0 :(得分:2)
使用Counter
肯定是最好的选择:
In [ ]: from collections import Counter
...: d = Counter(map(len, s))
...: d == {1:2, 6:2, 8:1, 2:1, 10:1}
Out[ ]: True
如果不使用"花哨的东西",我们使用生成器表达式,我认为同样有点奇特:
Counter(len(i) for i in s)
如果通常"通常"你的意思是使用for循环,我们可以这样做:
d = {}
for i in s:
if len(i) not in d:
d[len(i)] = 1
else:
d[len(i)] += 1
答案 1 :(得分:1)
只需对列表中的任何单词执行循环。在每次迭代中,如果长度不在dict中作为键,则创建值为1
的新键,否则增加键的先前值:
def list_to_dict(word_list):
d = dict()
for any_word in word_list:
length = len(any_word)
if length not in d:
d[length] = 1
else:
d[length] += 1
return d
答案 2 :(得分:0)
您可以使用字典理解来迭代s
,现在包含其原始元素的长度:
s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary']
final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)}
输出:
{1: 2, 6: 2, 8: 1, 2: 1, 10: 1}
简单地:
new_d = {}
for i in s:
new_d[len(i)] = 0
for i in s:
new_d[len(i)] += 1
输出:
{8: 1, 1: 2, 2: 1, 10: 1, 6: 2}