python - 如何将带有字数的列表转换为字典
问题描述
我想用一个字符串制作字典,并计算该字符串的单词。这就是我所做的,但它给了我一个错误!
book_text = "if it exists it should print"
for word in book_text:
word = book_text.split(" ")
print(word)
dictionary = {}
for i in word:
dictionary.values(i)
dictionary.keys(word.count(i))
print(dictionary)
错误说值需要多个元素
解决方案
如果键不存在,您可以使用setdefault
方法将键的值设置为 0。如果键已经存在,它将返回值。
初始变量
s = 'I want to make a dictionary using a string and count the words of that string'
a = [1, 2, 3, 2, 3]
d = {}
构建字典的不同方法
for xx in s:
d[xx] = 1 + d.get(xx, 0)
print(d)
另外,如果您不想使用该库,那么您可以这样做。
for xx in s: #same way we can use a
if xx not in d:
d[xx] = 1
else:
d[xx]+ = 1
我们可以再次使用更快的 Counter。
from collections import Counter
s = list(s)
print(Counter(s))
推荐阅读
- php - PhpStorm Xdebug:等待带有 ide 键“docker”的传入连接
- python - exec() 在我的定义中不起作用
- javascript - 如何删除动态 jQuery 手风琴元素
- verilog - 连续时钟周期中变量的异或
- php - 删除 WordPress 多站点子菜单中的管理评论链接
- c# - 如何使用新的输入系统在 Unity 中查找鼠标位置
- c++ - 在 C++ 中制作方形图案
- php - laravel 8 API:上传多张图片并用邮递员存储
- tensorflow - Keras:回调中的 tf.cond 以增加 KL_loss (VAE) 的损失权重
- java - 如何写子工厂链接到他们的总工厂(避免这些子工厂链接到另一个工厂)?