计算带有字典列表的列表中单词的出现频率



我想计算列表中每个唯一字符串的频率,然后将结果附加到字典列表中,将字符串保存为键,将值保存为字符串的频率。

一个例子是:输入:

word_list=["I","am","bob","I","am","hungry"]

输出:

dict_list=[{"I":2},{"am":2},{"bob":1},{"hungry":1}]

word_list=["I","am","bob","I","am","hungry"]
dict_list=[{"placeholder":0}]
for word in word_list:
for i in range(len(dict_list)):
if word not in dict_list[i].keys():
dict_list.append({word:1})
break
elif word in dict_list[i].keys():
dict_list[i][word]+=1
break
dict_list.pop(0)
print(dict_list)
#outputs is [{'I': 1}, {'am': 1}, {'bob': 1}, {'I': 1}, {'am': 1}, {'hungry': 1}]
#instead of [{"I":2},{"am":2},{"bob":1},{"hungry":1}]

代码:-

word_list=["I","am","bob","I","am","hungry"]
hashmap={}
for word in word_list:
hashmap[word]=hashmap.get(word,0)+1    
print(hashmap)

输出: -

{'I': 2, 'am': 2, 'bob': 1, 'hungry': 1}

您可以使用:

from collections import Counter
out = [{k:v} for k,v in Counter(word_list).items()]
# or
# out = [dict([x]) for x in Counter(word_list).items()]

输出:[{'I': 2}, {'am': 2}, {'bob': 1}, {'hungry': 1}]

但是老实说,把一个字典分解成一个单条目字典的列表有什么意义呢?

Counter(word_list)的输出更有用:

Counter({'I': 2, 'am': 2, 'bob': 1, 'hungry': 1})

可以使用集合。计数器和列表推导式在一行中生成结果,如下所示:

from collections import Counter
word_list=["I","am","bob","I","am","hungry"]
dict_list = [{key: value} for key, value in Counter(word_list).items()]
print(dict_list)
输出:

[{'I': 2}, {'am': 2}, {'bob': 1}, {'hungry': 1}]

您可以从collections导入Counter,并为word_list设置Couter,然后将其转换为dict:

from collections import Counter
dict_list=Counter(word_list)
dict_list=dict(dict_list)
print(dict_list)

>>> {'I': 2, 'am': 2, 'bob': 1, 'hungry': 1}

相关内容

  • 没有找到相关文章

最新更新