Python在collections模块中具有Counter类。它是用于计数可哈希对象的类。例如。:

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 - 相当于Ruby中的Python计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33828449/

10-12 22:04