python - 以有效的方式组合项目列表
问题描述
我正在尝试使用一些 Python 科学库查找是否有更有效的方法来查找这些组合。
我试图避免本地for
循环和列表追加,更喜欢使用一些 NumPy 或类似的功能,理论上应该更有效,因为它在后台使用 C 代码。我正在努力寻找一个,但对我来说,以一种有效的方式而不是使用缓慢的 Python 原生结构来进行这些操作是一个很常见的问题。
我想知道我是否在寻找错误的地方?例如,这在这里似乎没有帮助:https ://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.binomial.html
请参阅此处,我从下限 2 开始获取长度为 5 的列表的二项式系数,并找出所有可能的组合。同时,我追加到一个全局列表,这样我就可以从原始输入列表中获得一个很好的“已获取项目”列表。
import itertools
input_list = ['a', 'b', 'c', 'd', 'e']
minimum_amount = 2
comb_list = []
for i in range(minimum_amount, len(input_list)):
curr_list = input_list[:i+1]
print(f"the current index is: {i}, the lists are: {curr_list}")
curr_comb_list = list(itertools.combinations(curr_list, i))
comb_list = comb_list + curr_comb_list
print(f"found {len(comb_list)} combinations (check on set length: {len(set(comb_list))})")
print(comb_list)
给出:
found 12 combinations (check on set length: 12)
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'd'),
('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd'), ('a', 'b', 'c', 'e'),
('a', 'b', 'd', 'e'), ('a', 'c', 'd', 'e'), ('b', 'c', 'd', 'e')]
- 是否有可能避免
for
循环并使用一些科学库来更快地做到这一点? - 我怎样才能更快地做到这一点?
解决方案
最终列表包含从 1 到 任意长度的所有组合len(input_list)
,这实际上是Power Set。
查看如何获取列表元素的所有可能组合?.
推荐阅读
- javascript - 从 HDD 读取 HTML 文本文件不显示任何结果
- node.js - mongoose.findOne 返回 null
- github - 如何找到与 Heroku 应用关联的 github 存储库?
- java - 为 BigDecimal 使用正确的注释
- sql - 按 2 列分组,同时对集合中的缺失行使用默认值
- awk - awk : 有条件的恢复线
- java - 如何用新列表替换 ListView 的列表
- python - 结合 Python Flask Jinja2 和 Mustache
- java - 嵌套 JavaFX 的 TreeView 的有效数量
- php - 如何正确处理 symfony API 请求中的异常