我有一组 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/