python - 从没有循环的计数器列表中更新计数器?
问题描述
我有一个计数器列表:
from collections import Counter
counters = [
Counter({"coach": 1, "says": 1, "play": 1, "basketball": 1}),
Counter({"i": 2, "said": 1, "hate": 1, "basketball": 1}),
Counter({"he": 1, "said": 1, "play": 1, "basketball": 1}),
]
我可以使用如下所示的循环组合它们,但我想避免循环。
all_ct = Counter()
for ct in counters:
all_ct.update(ct)
使用reduce
会报错:
all_ct = Counter()
reduce(all_ct.update, counters)
>>> TypeError: update() takes from 1 to 2 positional arguments but 3 were given
有没有办法在不使用循环的情况下将计数器组合成一个计数器?
解决方案
你可以使用求和功能。
all_ct = sum(counters, Counter())
推荐阅读
- ios - 想要从 avplayer 获取视频当前播放时间和视频总时间
- uri - URI 方案与协议
- logging - 一旦 jboss-eap-7.1.0 开始部署 5.3.8 版的 cas.war,它就会停止记录 serverstartup 日志
- javascript - 如何检查Javascript对象值是否为数组而不是空
- node.js - nodejs 抛出 TypeError: process.uptime is not a function
- android - 引起:android.database.DatabaseUtils.readExceptionFromParcel 的 android.database.sqlite.SQLiteException
- mule - 组合数组的元素并重新格式化输出
- reactjs - React 样式最佳实践。全局或组件级别
- sql - 每月需要将单行转换为多行
- symfony - 交响乐。如何构建表格?