首页 > 解决方案 > Python Collection Counter减法与'-'

问题描述

我是 pythonic 风格解决方案的新手,我正在尝试了解如何阅读以下代码,或了解实际发生的情况

给定:

s = "bab"
t = "aba"

s_counter = Counter(s) # Counter({'b': 2, 'a': 1})
t_counter = Counter(t) # Counter({'a': 2, 'b': 1})

有什么区别

print((s_counter - t_counter)) # Counter({'b': 1})

versus

s_counter.subtract(t_counter)
print(s_counter) # Counter({'b': 1, 'a': -1})

当您运行该代码时实际发生了什么?在减法()函数上,它似乎基本上抓住了每个键并用 t_counter 值找到减法 s_counter 值。但我不确定

print((s_counter - t_counter))

标签: pythonpython-3.x

解决方案


.subtract方法在对象上就地工作,Counter接受映射(例如dictCounters)或任意迭代。此外,它允许非正值。

-运算符创建一个新的计数器对象,并且只包含正结果(结果中忽略 0 和负值)。它只适用于Counter对象之间。

.update方法和操作员之间存在类似的关系+


推荐阅读