python - Python:在不构建列表的情况下运行迭代器值的计数
问题描述
我想计算迭代器的唯一值,但不必先构建列表。使用列表,我会做例如:
from collections import Counter
from itertools import combinations
my_counts = Counter([sum(x) for x in combinations([1,2,3,4,5])],2)
但在上面,列出了一个列表,然后Counter
应用。但是有没有办法保持一个运行的计数,这样整个列表就不需要存储在内存中了?
解决方案
只需输入Counter
a 生成器表达式而不是 a list
:
my_counts = Counter(sum(x) for x in combinations([1,2,3,4,5], 2))
甚至更短(但map
仅在 Python3 中返回生成器):
my_counts = Counter(map(sum, combinations([1,2,3,4,5], 2)))
这不会首先在内存中建立一个列表。
推荐阅读
- python - 你如何让生成器释放一个值?
- python - 从两个列表中创建字典时,分配中的类型不兼容
- hyperledger-fabric - 错误:事件服务超时 - 无法开始侦听
- react-native - 如何将这个基于类的组件转换为无状态组件?
- typescript - 如何使用 TypeScript 为 Nuxt 路由添加钩子?
- c++ - 如何从位于不同文件夹中的头文件和源文件构建库?
- java - Cucumber,Java:特定文件中的步骤定义忽略
- python - 从python中的wikidata获取实体名称/标签
- python - 如何通过 python 正确更新 Google Sheet 图表数据范围?
- cookies - 使用 Postman Collection 导出 Cookie