python - 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))
解决方案
该.subtract
方法在对象上就地工作,并Counter
接受映射(例如dict
或Counter
s)或任意迭代。此外,它允许非正值。
-
运算符创建一个新的计数器对象,并且只包含正结果(结果中忽略 0 和负值)。它只适用于Counter
对象之间。
.update
方法和操作员之间存在类似的关系+
。
推荐阅读
- node.js - AWS Lambda 仅在满足条件时触发函数
- firebase - Firebase 身份验证重定向到 Google 登录页面到 Vue 路由器
- python - 具有等效字符串的清洁列
- amazon-web-services - 包含 Spot 实例的 AutoScaling 组是否会响应 Spot 实例中断通知?
- php - “ldap_bind():无法绑定到服务器:凭据无效”,凭据正确
- css - 在移动设备上查看时,SVG 图像回退到 Times New Roman?
- c# - 显示来自foreach循环的许多图片后如何在视图数据中显示获取项目ID
- java - 双重嵌套事务的回滚绕过保存点
- shell - 在目录/子目录中查找 .XML 文件的数量
- c++ - IPv6 client can't connect to IPv6 server