python - 相当于 Python 在 Ruby 中的计数器

标签 python ruby

Python 有 Counter collections 模块中的类。它是一个用于计算可散列对象的类。例如:

cnt = Counter()
cnt['Anna'] += 3
cnt['John'] += 2
cnt['Anna'] += 4
print(cnt)
=> Counter({'Anna': 7, 'John': 2})
print(cnt['Mario'])
=> 0

Ruby 中的 Counter 是什么?

编辑:

Counter 类还提供了以下数学运算和辅助方法:

c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d 
=> Counter({'a': 4, 'b': 3})
c - d
=> Counter({'a': 2})
c.most_common(1)
=> ['a']

最佳答案

cnt = Hash.new(0)
cnt["Anna"] += 3
cnt["John"] += 2
cnt["Anna"] += 4
cnt # => {"Anna" => 7, "John" => 2}
cnt["Mario"] #=> 0

c = {"a" => 3, "b" => 1}
d = {"a" => 1, "b" => 2}
c.merge(d){|_, c, d| c + d} # => {"a" => 4, "b" => 3}
c.merge(d){|_, c, d| c - d}.select{|_, v| v > 0} # => {"a" => 2}
c.max(1).map(&:first) # => ["a"]

关于python - 相当于 Python 在 Ruby 中的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33828449/

相关文章:

ruby 彩虹/ unicorn 开始 faye and rails

ruby - 如何在ruby中读取图像文件

python - Boto Route53 或 Area53 - 如何将多个 IP 地址添加到子域

python - 使用 NetworkX 计算 SimRank?

执行 3d 图时 python 卡住

ruby - 在 Ruby 中使用哈希作为工厂

ruby-on-rails - 如何渲染部分表单的验证错误 - Rails

ruby-on-rails - 通用路由匹配 ':controller(/:action(/:id))(.:format)' 在 Rails 4 中不可用。出路?

python - 扭曲的 deferToThread,不适用于 Mock.patch()

python - 使用 re.findall() 匹配包含特殊字符的术语?