python - 如何连接字符串计数和 Int

标签 python string integer

我有一组 set 形式的字符串计数,我想将它除以某个 int 值。

例子:

 Counter({'dlr': 21, 'said': 18, 'total': 17, 'bankamerica': 13, 'bank': 11, 'analyst': 9, 'prev': 9, 'februari': 8, 'york': 8, 'would': 8, 'price': 8, 'time': 8, 'wheat': 7})

我想将它除以某个 int 值,这样我就能得到 count 除以该 int 值的单词。

我收到 TypeError: cannot concatenate 'str' and 'int' objects.

最佳答案

用字典理解建立一个新的计数器:

>>> counter = Counter({'dlr': 21, 'said': 18, 'total': 17, 'bankamerica': 13, 'bank': 11, 'analyst': 9, 'prev': 9, 'februari': 8, 'york': 8, 'would': 8, 'price': 8, 'time': 8, 'wheat': 7})
>>> counter2 = Counter({k:v/2 for k,v in counter.items()})
>>> counter2
Counter({'dlr': 10, 'said': 9, 'total': 8, 'bankamerica': 6, 'bank': 5, 'would': 4, 'price': 4, 'februari': 4, 'york': 4, 'time': 4, 'prev': 4, 'analyst': 4, 'wheat': 3})

如果您不想进行整数除法:

>>> from __future__ import division
>>> counter2 = Counter({k:v/2 for k,v in counter.items()})
>>> counter2
Counter({'dlr': 10.5, 'said': 9.0, 'total': 8.5, 'bankamerica': 6.5, 'bank': 5.5, 'prev': 4.5, 'analyst': 4.5, 'would': 4.0, 'price': 4.0, 'februari': 4.0, 'york': 4.0, 'time': 4.0, 'wheat': 3.5})

关于python - 如何连接字符串计数和 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684926/

相关文章:

python - 在 Matplotlib 中从一组重叠的艺术家中挑选一位艺术家

python - 更改马赛克图的默认颜色

ruby - 为什么 Str[fix_num] 产生错误的结果

string - "set foo to text returned of"代表数字吗?

python - 根据值和规则拆分整数列表的更好方法

c - C 中的字符串/整数关联

python - Django 模型 OneToOneField : "This field is required" error in admin

java - 如何从这样的字符串中提取 double

string - 如何在 MATLAB 中搜索元胞数组中的字符串?

python - 在 sizer 中获取鼠标位置? wxpython